我们之前学了动态代理,而关于实物这块,在每个service方法中总就那么几句话,而且地方也是固定的,所以我们也考虑用动态代理来解决它,只是在spring中,框架已经为我们写好了通知类,我们直接配置就好了,跟之前AOP配置稍微有点不同,事务有它自己的配法,不过也差不多,看代码:
这是我写的一个方法,模拟转账:
public void changeMoney(int i,int j,int money){
jt.update("update user set money = money - ? where id = ?", money,i);
int x = 1/0;
jt.update("update user set money = money + ? where id = ?", money,j);
}
不配置事务时,i 的钱减少了,而 j 的钱没有增多。
现在我们在xml文件添加事务控制配置:
注意配置事务标签先要导入相关约束及 jar 包
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<!-- 第二步:配置通知,但因为你要写的那几个通知什么时候执行怎么执行都是固定的,所以spring帮我们写了 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 第三步:配置事务的属性,具体参照下面的图 -->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 第四步:配置通知和切入点的关系,形成一个完整的切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.dimples.*.impl.*.*(..))"/>
</aop:config>
</beans>
可以看到配置方法其实和原始的AOP配置很像,只不过多出了事务属性的配置。下面这是事务属性详解:
然后我们还可以使用XML搭配注解的方式来配置事务:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
然后在需要事务的方法上加注解就行了:
@Transactional
public void changeMoney(int i,int j,int money){
jt.update("update user set money = money - ? where id = ?", money,i);
int x = 1/0;
jt.update("update user set money = money + ? where id = ?", money,j);
}
注解可以写在接口上、类上、方法上。写在接口上代表所有实现类都有事务,写在类上表示所有方法都有事务,写在方法上则表示该方法有事务,优先级遵循就近原则!至于事务的属性,我们可以在@Transactionl后面跟着配置。