beab.xml配置
<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/testdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="admin123"></property>
</bean>
<!--
1.配置【事务管理器】
2.配置【事务通知】
3.配置【AOP中的通用切入点表达式】
4.建立【AOP的通用切入点表达式和事务通知】和【事务通知】的关系
5.配置【事务属性】
-->
<!--1.配置事务管理器-->
<bean id="tranManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2.配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="tranManager">
<!--5.配置【事务属性】
isolation:指定事务的隔离级别,默认;default
propagation:指定事务的传播行为,默认:REQUIRED(增删改) 标识一定会有事务,SUPPORTS(查询)
read-only:指定事务是否只读,默认:false
timeout:指定事务的超时时间,默认:-1 永不超时 秒为单位
rollback-for:指定一个异常时,如果发生,该异常回滚,其他异常不回滚 默认:任何异常都回滚
no-rollback-for:指定一个异常时,如果发生,该异常不回滚,其他异常回滚 默认:任何异常都回滚
-->
<tx:attributes>
<tx:method name="exChangeScoreProxy" propagation="REQUIRED" read-only="false"></tx:method>
<!-- <tx:method name="get*" propagation="SUPPORTS" read-only="true"></tx:method>-->
</tx:attributes>
</tx:advice>
<!--3.配置AOP中的通用切入点表达式-->
<aop:config>
<aop:pointcut id="express" expression="execution(* com.study.serviceimp.*.*(..))"/>
<!--4.建立【AOP的通用切入点表达式和事务通知】和【事务通知】的关系-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="express"></aop:advisor>
</aop:config>
1.关联了事务控制的方法
public Integer exChangeScoreProxy(Integer id, Integer idTemp) {
Integer result = null;
try {
result = null;
result = 0;
System.out.println("TUserServiceImp-exChangeScoreProxy方法执行了。。。");
//1
TUser user = itUser.getRow(id);
//2
TUser userTemp = itUser.getRow(idTemp);
BigDecimal num = user.getT_score();
BigDecimal numTemp = userTemp.getT_score();
user.setT_score(numTemp);
userTemp.setT_score(num);
//3
result += itUser.updateScore(user);
//异常点
int number = 1 / 0;
//4
result += itUser.updateScore(userTemp);
} catch (Exception e) {
/**********************1.不能打印,否则会让事务管理器无效,无法回滚**********************/
//e.printStackTrace();
/**********************2.只能抛出运行时异常,才会让事务管理器有效,可以回滚**********************/
throw new RuntimeException(e);
}
return result;
}
2.注入了AOP切面的Around方法
@Around("express()")
public Object around(ProceedingJoinPoint proc) {
Object result = null;
try {
logBefore();
Object[] args = proc.getArgs();
result = proc.proceed(args);
logAfter();
} catch (Throwable throwable) {
logAfterThrow();
/**********************1.不能打印,否则会让事务管理器无效,无法回滚**********************/
//throwable.printStackTrace();
/**********************2.只能抛出运行时异常,才会让事务管理器有效,可以回滚**********************/
throw new RuntimeException(throwable);
} finally {
logAfterReturn();
}
return result;
}
解释:catch方法中只能抛出运行时异常RuntimeException,不能打印或者抛出其他类型异常,也不能加finally