SpringBoot如何注解事务声明式事务
2018-07-03 · 国内最优秀java资源共享平台
springboot的事务也主要分为两大类,
一是xml声明式事务,
二是注解事务,注解事务也可以实现类似声明式事务的方法,
springboot 之 xml事务
使用 @ImportResource("classpath:transaction.xml") 引入该xml的配置
springboot 注解事务
Transactional注解事务
注:需要在进行事物管理的方法上添加注解@Transactional,或者偷懒的话直接在类上面添加该注解
注解声明式事务
@Configuration
public class TxConfigBeanName {
@Autowired
private DataSourceTransactionManager transactionManager;
// 创建事务通知
@Bean(name = "txAdvice")
public TransactionInterceptor getAdvisor() throws Exception {
Properties properties = new Properties();
properties.setProperty("get*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("add*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("save*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("update*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception,readOnly");
TransactionInterceptor tsi = new TransactionInterceptor(transactionManager,properties);
return tsi;
}
@Bean
public BeanNameAutoProxyCreator txProxy() {
BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
creator.setInterceptorNames("txAdvice");
creator.setBeanNames("*Service", "*ServiceImpl");
creator.setProxyTargetClass(true);
return creator;
}
}