使用注解配置spring声明式事务相比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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.com.lzxh"/>
<!-- 引入外部资源 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${jdbc.userName}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- <property name="dataSource" ref="dataSource"/> -->
<constructor-arg ref="dataSource"/>
</bean>
<!-- 事务管理的注解驱动 -->
<tx:annotation-driven proxy-target-class="true"/>
</beans>
业务类中,可以配置全局的事务,配置在类名上,则当前类都受事务控制,也可以为某个需要事务的方法单独配置事务,如下:
package cn.com.lzxh.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.com.lzxh.dao.UserDao;
import cn.com.lzxh.pojo.User;
import cn.com.lzxh.service.UserServcie;
@Service("userService")
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public class UserServiceImpl implements UserServcie {
@Autowired
private UserDao userDao;
@Override
public void saveUser() {
}
@Override
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public Integer updateUser() {
userDao.updateUser("张三3", 1);
//int x = 1 / 0;
userDao.updateUser("李四3", 2);
return null;
}
@Override
public void selectUser() {
List<User> list1 = userDao.selectUser();
List<User> list2 = null;
try {
int x = 1 / 0;
list2 = userDao.selectUser();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(list1);
System.out.println(list2);
}
}
}
至此,声明式事务的注解配置已完成,过程相比XML配置更简单。