今天接着来记录下Spring的声明式事务控制。
Spring有两种控制事务的方式,分别是声明式的和函数式的。
声明式的是以配置为主,而函数式的以代码为主。后者的复用性特别差,重复代码特别多,所以在开发中用的比较少。而声明式事务控制又有基于xml和注解的两种实现方式,今天记录下基于xml声明式的事务控制。
一般事务控制是在业务层进行的,在三层架构中事务控制处在Service层内。比较经典的事务控制案例是银行的转账操作,如果一旦发生异常我们需要保持数据库的一致性,我们以前编写这方面代码时,往往自己编写事务控制的方法,在我上一个博客中已经记录的动态代理控制事务。
这遍主要介绍Spring为我们整合的事务控制.
在pom.xml中引入依赖:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
接着在xml文件中配置,我们首先需要引入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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
接着我们需要一个TransactionManager,即事务管理器:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/demo"></property>
<property name="username" value="root"></property>
<property name="password" value="***"></property>
</bean>
而事务管理器又需要dataSource,这里我们选用Spring内置的数据源。
配置完事务管理器后,我们就开始配置通知内容了。因为事务控制也是基于AOP的,所以也有通知:
<tx:advice id="demoTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save" timeout="-1" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="all" expression="execution( * service.impl.*.*(..))"/>
<aop:advisor advice-ref="demoTxAdvice" pointcut-ref="all"></aop:advisor>
</aop:config>
aop的操作大同小异,配置切入点表达式那些,还有指定通知.
接着就可以测试了,疫情还没结束,大家想着少出门哦.