springBoot项目的事务管理

本文介绍SpringBoot项目中事务管理的多种实现方式,包括使用注解、XML配置、Java配置类等,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.springBoot项目的事务管理

说明:感谢原作者分享。。参考连接:http://www.jb51.net/article/122643.htm

作者有亲测java配置方式一可行,其它几种方式未亲测。。故贴出其代码及出处供参考!

springboot类似于springmvc可以将事务的处理交由spring框架进行管理,避免自己写代码实现事务管理;

springboot项目事务管理主要有以下几种方式:

1.在需要更新数据库数据的service方法上增加@transactional(rollbackfor={Exception.class}),进行事务的管理及回滚.
当然这其中可以配置的属性还有传播行为,事务的只读属性等。。
2.上面第一点需要在事务增强的方法上写注解,或者统一在需要的类上进行声明。比较繁琐,如果有漏写会存在数据不一致的风险!!所以推荐:
统一使用声明式事务进行统一的管理:
2.1 springboot 之 xml事务,代码及配置如下:
可以使用 @ImportResource("classpath:transaction.xml") 引入该xml的配置,xml的配置如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
  <bean id="txManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" ></property>
  </bean>
  <tx:advice id="cftxAdvice" transaction-manager="txManager">
    <tx:attributes>
      <tx:method name="query*" propagation="SUPPORTS" read-only="true" ></tx:method>
      <tx:method name="get*" propagation="SUPPORTS" read-only="true" ></tx:method>
      <tx:method name="select*" propagation="SUPPORTS" read-only="true" ></tx:method>
      <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" ></tx:method>
    </tx:attributes>
  </tx:advice>
   <aop:config>
    <aop:pointcut id="allManagerMethod" expression="execution (* com.exmaple.fm..service.*.*(..))" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" order="0" />
  </aop:config>

springboot 启动类如下:
package com.example.fm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource("classpath:transaction.xml")
@SpringBootApplication
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}
2.2 使用java配置类进行事务管理配置  
方式一(推荐):
package com.zhiche.opbaas.config;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import java.util.Properties;
@Configuration   //这里使用Component或Configuration事务都可以生效
public class TransactionalConfigForBoot {
    private DataSourceTransactionManager transactionManager;
    @Autowired
    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    // 创建事务通知
    @Bean(name = "txAdvice")
    public TransactionInterceptor getAdvisor() {
        Properties properties = new Properties();
        properties.setProperty("get*", "PROPAGATION_NOT_SUPPORTED,-Exception,readOnly");
        properties.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("save*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        return new TransactionInterceptor(transactionManager, properties);
    }
    @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        creator.setInterceptorNames("txAdvice");
        creator.setBeanNames("*Service", "*ServiceImpl");
        creator.setProxyTargetClass(true);
        return creator;
    }
}

方式二:
package com.exmple.service.fm9.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
 * Created by guozp on 2017/8/28.
 */
@Aspect
//@Component 事务依然生效
@Configuration
public class TxAdviceInterceptor {
  private static final int TX_METHOD_TIMEOUT = 5;
  private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.alibaba.fm9..service.*.*(..))";
  @Autowired
  private PlatformTransactionManager transactionManager;
  @Bean
  public TransactionInterceptor txAdvice() {
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
     /*只读事务,不做更新操作*/
    RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
    readOnlyTx.setReadOnly(true);
    readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED );
    /*当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务*/
    RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
    requiredTx.setRollbackRules(
      Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
    requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    requiredTx.setTimeout(TX_METHOD_TIMEOUT);
    Map<String, TransactionAttribute> txMap = new HashMap<>();
    txMap.put("add*", requiredTx);
    txMap.put("save*", requiredTx);
    txMap.put("insert*", requiredTx);
    txMap.put("update*", requiredTx);
    txMap.put("delete*", requiredTx);
    txMap.put("get*", readOnlyTx);
    txMap.put("query*", readOnlyTx);
    source.setNameMap( txMap );
    TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
    return txAdvice;
  }
  @Bean
  public Advisor txAdviceAdvisor() {
    AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
    return new DefaultPointcutAdvisor(pointcut, txAdvice());
    //return new DefaultPointcutAdvisor(pointcut, txAdvice);
  }
}

方式三:
package com.exmple.service.fm9.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
 * Created by guozp on 2017/8/29.
 */
//@Component 事务依然生效
@Configuration
public class TxAnoConfig {
  /*事务拦截类型*/
  @Bean("txSource")
  public TransactionAttributeSource transactionAttributeSource(){
    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
     /*只读事务,不做更新操作*/
    RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
    readOnlyTx.setReadOnly(true);
    readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED );
    /*当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务*/
    //RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
    //requiredTx.setRollbackRules(
    //  Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
    //requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED,
      Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
    requiredTx.setTimeout(5);
    Map<String, TransactionAttribute> txMap = new HashMap<>();
    txMap.put("add*", requiredTx);
    txMap.put("save*", requiredTx);
    txMap.put("insert*", requiredTx);
    txMap.put("update*", requiredTx);
    txMap.put("delete*", requiredTx);
    txMap.put("get*", readOnlyTx);
    txMap.put("query*", readOnlyTx);
    source.setNameMap( txMap );
    return source;
  }
  /**切面拦截规则 参数会自动从容器中注入*/
  @Bean
  public AspectJExpressionPointcutAdvisor pointcutAdvisor(TransactionInterceptor txInterceptor){
    AspectJExpressionPointcutAdvisor pointcutAdvisor = new AspectJExpressionPointcutAdvisor();
    pointcutAdvisor.setAdvice(txInterceptor);
    pointcutAdvisor.setExpression("execution (* com.alibaba.fm9..service.*.*(..))");
    return pointcutAdvisor;
  }
  /*事务拦截器*/
  @Bean("txInterceptor")
  TransactionInterceptor getTransactionInterceptor(PlatformTransactionManager tx){
    return new TransactionInterceptor(tx , transactionAttributeSource()) ;
  }
} 

方式四:(待确认,不推荐)
ackage com.alibaba.fm9.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
 * Created by guozp on 2017/8/28.
 *            
 */
@Configuration //事务失效,都移动到一个方法不失效
//@Component // 事务可行,不用都移动到一个方法
public class TxOtherConfigDefaultBean {
  public static final String transactionExecution = "execution (* com.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;
  }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值