(学习笔记仅帮助自己理解记忆,部分内容可能存在理解错误,如有发现,还望指出)
Spring的事务管理机制实现的原理,就是通过一个动态代理对所有需要事务管理的Bean进行加载,并根据配置在invoke方法中对当前调用的
方法名进行判定,并在method.invoke方法前后为其加上合适的事务管理代码,这样就实现了Spring式的事务管理。
Spring中的AOP实 现更为复杂和灵活,不过基本原理一致
事务读取类型
事务传播行为
1.标志REQUIRES_NEW会新开启事务,外层事务不会影响内部事务的提交/回滚
2.标志REQUIRES_NEW的内部事务的异常,会影响外部事务的回滚
事务隔离级别
代码演示
示例结构:
示例说明:
mapper------定义存钱与取钱2个方法
//存款
Integer deposit(@Param("money")Double money,
@Param("act") Integer act);
//取款
Integer take(@Param("money")Double money,
@Param("act") Integer act);
service-------模拟取钱事务
//存款
void deposit(Double money,Integer act1,Integer act2) throws IOException;
service实现类-------模拟取钱事务
private BankMapper bm;
public void deposit(Double money, Integer act1, Integer act2) throws IOException {
bm.deposit(money,act1);
bm.take(money,act2);
throw new IOException("手动运行时异常.....");
}
ApplicationContext核心配置文件编写:
<!--事务管理器 管理制定的事务规则,应用到相关方法上-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事务增强 制定事务规则-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="select*" propagation="SUPPORTS"/>
<tx:method name="find*" propagation="SUPPORTS"/>
<tx:method name="get*" propagation="SUPPORTS"/>
<!--rollback-for="java.io.IOException"-->
<tx:method name="*" propagation="REQUIRED" no-rollback-for="java.io.IOException"/>
</tx:attributes>
</tx:advice>
<!--应用到业务上,,,,,,,,,配置切面-->
<aop:config proxy-target-class="true">
<aop:pointcut id="txAdv" expression="execution(* CLASS.service.BankServiceImpl.deposit(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txAdv"></aop:advisor>
</aop:config>
测试类代码:
@org.junit.Test
public void demo1(){
ApplicationContext act = new ClassPathXmlApplicationContext("ApplicationContext.xml");
BankService bs = (BankService) act.getBean("bsi");
try {
bs.deposit(500.0,1,2);
} catch (IOException e) {
e.printStackTrace();
}
}
使用注解配置事务
ApplicationContext核心配置文件编写:
<!--事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启对事务注解的支持-->
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"></tx:annotation-driven>
实现类:
@Service("bsi")
@Transactional
public class BankServiceImpl implements BankService {
@Autowired
private BankMapper bm;
@Override
@Transactional(propagation = Propagation.REQUIRED,noRollbackFor = IOException.class)
public void deposit(Double money, Integer act1, Integer act2) throws IOException {
bm.deposit(money,act1);
bm.take(money,act2);
throw new IOException("手动运行时异常.....");
}
public BankMapper getBm() {
return bm;
}
public void setBm(BankMapper bm) {
this.bm = bm;
}
}