###初始化类###
类注解
@Configuration @ComponentScan(basePackages = AppConfig.BASEPACKAGE,excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class,RestController.class}) }) public class RootConfiguration {
1.采用注解式事务,需要在类加添加@EnableTransactionManagement
@Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); }
2.拦截器式
@Bean(name="transactionManager") public DataSourceTransactionManager transactionManager(DataSource dataSource) { DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); transactionManager.setDataSource(dataSource); transactionManager.setGlobalRollbackOnParticipationFailure(false); return transactionManager; } @Bean(name="transactionInterceptor") public TransactionInterceptor transactionInterceptor(DataSourceTransactionManager transactionManager) { TransactionInterceptor transactionInterceptor = new TransactionInterceptor(); transactionInterceptor.setTransactionManager(transactionManager); Properties properties = new Properties(); properties.setProperty("*","PROPAGATION_required,ISOLATION_DEFAULT,-Exception"); transactionInterceptor.setTransactionAttributes(properties); return transactionInterceptor; } @Bean(name="beanNameAutoProxyCreator") public BeanNameAutoProxyCreator beanNameAutoProxyCreator() { BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator(); beanNameAutoProxyCreator.setProxyTargetClass(true); beanNameAutoProxyCreator.setBeanNames("*Service"); beanNameAutoProxyCreator.setInterceptorNames("transactionInterceptor"); return beanNameAutoProxyCreator; }
###注意事项###
在某个方法依赖另外一个bean
时,不可以直接调用生成bean
的方法。如以上依赖dataSource
的地方较多,不可以直接调用dataSource()
方法,否则会生成多个实例,导致最后事务不成功,实际使用的可能是实例A,但事务管理到的可能是实例B,从日志中看一切正常,也调用了doRollBack
的。但在跟踪代码时会发现在TransactionSynchronizationManager.getSynchronizations()
返回了两个,分别为:org.mybatis.spring.sqlSessionUtils$sqlSessionSynchronization@ff5c61f
,org.springframework.jdbc.datasource.DataSourceUtils$ConnectionSynchronization@4545f833
。官方文档里面直接调用方法的http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html,不知道是否可以通过什么方式实现这种直接调用
正确的获取方式为:
1.直接通过参数传递需要的依赖
2.参数传递Listablebeanfactory
,通过这个获取