springboot 对新人来说可能上手比springmvc要快,但是对于各位从springmvc转战到springboot的话,有些地方还需要适应下,尤其是xml配置。我个人是比较喜欢注解➕xml是因为看着方便,查找方便,清晰明了。但是xml完全可以使用注解代替,今天就扒一扒springboot中事务使用注解的玩法。
springboot的事务也主要分为两大类,一是xml声明式事务,二是注解事务,注解事务也可以实现类似声明式事务的方法,关于注解声明式事务,目前网上搜索不到合适的资料,所以在这里,我将自己查找和总结的几个方法写到这里,大家共同探讨
springboot 之 xml事务
可以使用 @ImportResource("classpath:transaction.xml") 引入该xml的配置,xml的配置如下
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://.alibaba.fm9..service.*.*(..))"; @Autowired private PlatformTransactionManager transactionManager; //@Bean //@ConditionalOnMissingBean //public PlatformTransactionManager transactionManager() { // return new DataSourceTransactionManager(dataSource); //} @Bean public TransactionInterceptor transactionInterceptor() { Properties attributes = new Properties(); attributes.setProperty("get*", "PROPAGATION_REQUIRED,-Exception"); attributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception"); attributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception"); attributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception"); //TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager(), attributes); TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, attributes); return txAdvice; } //@Bean //public AspectJExpressionPointcut aspectJExpressionPointcut(){ // AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); // pointcut.setExpression(transactionExecution); // return pointcut; //} @Bean public DefaultPointcutAdvisor defaultPointcutAdvisor(){ //AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); //pointcut.setExpression(transactionExecution); //DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(); //advisor.setPointcut(pointcut); //advisor.setAdvice(transactionInterceptor()); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(transactionExecution); DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(); advisor.setPointcut(pointcut); Properties attributes = new Properties(); attributes.setProperty("get*", "PROPAGATION_REQUIRED,-Exception"); attributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception"); attributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception"); attributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception"); TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, attributes); advisor.setAdvice(txAdvice); return advisor; }}简单来说,springboot使用上述注解的几种方式开启事物,可以达到和xml中声明的同样效果,但是却告别了xml,使你的代码远离配置文件。
总结
以上所述是小编给大家介绍的SpringBoot 注解事务声明式事务的方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!