1.
配置事务管理器
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="dataSourceTransactionManager">
<property name="dataSource" ref="Datasource"></property>
</bean>
2.开启事务注解
引入命名空间tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
开启事务注解
<tx:annotation-driven transaction-manager="dataSourceTransactionManager" ></tx:annotation-driven>
配置好的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<bean id="Datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql:///account"></property>
<property name="username" value="root"></property>
<property name="password" value="mysql"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
</bean>
<bean id="JdbcTample" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="Datasource"></property>
</bean>
<context:component-scan base-package="org.hxut.zyk" ></context:component-scan>
<!--创建事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="dataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="Datasource"></property>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager" ></tx:annotation-driven>
</beans>
3.在要添加的事务的类上添加注解
@Transactional
这个注解加到类上:类中的所有方法都增加了事务
这个注解加到方法上:此方法添加了事务
注意:如果要添加的事务的类实现了一个接口,则需要在xml文件中加aop约束并加一句
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
原因还不知道,可能是动态代理造成
package org.hxut.zyk.service;
import org.hxut.zyk.dao.AccountdaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
AccountdaoImpl accountdao;
public void change()
{
accountdao.add_lucky();
int a=10/0;
accountdao.less_mercy();
}
}