spring事务配置


返回目录

SpringBoot推荐事务采用@Transactional注解进行配置。使用方式如下:

@Transactional
@Override
public void save() {
    User user = new User("苍老师");
    userMapper.insertSelective(user);
}

全局事务配置:

第一种方式: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="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="mod*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="up*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="set*" propagation="REQUIRED"/>
            <tx:method name="change*" propagation="REQUIRED"/>
            <tx:method name="logout*" propagation="REQUIRED"/>
            <tx:method name="login*" propagation="REQUIRED"/>
            <tx:method name="check*" propagation="REQUIRED"/>
            <tx:method name="tiJiao*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="init*" read-only="true"/>
            <tx:method name="timing*" propagation="REQUIRED"/>
            <tx:method name="execute*" propagation="REQUIRED"/>
            <tx:method name="execute*" propagation="REQUIRED"/>
            <tx:method name="send*" propagation="REQUIRED"/>
            <tx:method name="batch*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <!-- 切入点 -->
        <aop:pointcut id="newServicesPointcut"
                      expression="execution(* com.esl.ce.*.*.service..*.*(..))  or execution (* com.esl.ce.*.*.*.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="newServicesPointcut"/>
    </aop:config>
</beans>

注:切入点一定要和自己项目中的目录结构对应,execution(* com.esl.ce...service….(…)),.*代表一层目录。

第二种方式:java类配置事务

package com.esl.ce.web.common.util;
 
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.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.*;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
/**
 * springboot 之 注解式声明事务,使用声明式事务配置
 * @author Administrator
 */
@Configuration
public class ApplicationContextTransactional {
 
    //事务方法超时时间设置
    private static final int TX_METHOD_TIMEOUT=10;
 
    //AOP切面的切点表达式
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.esl.ce.*.*.service..*.*(..))  or execution (* com.esl.ce.*.*.*.service..*.*(..))";
 
    //注入事务管理器
    @Autowired
    private PlatformTransactionManager transactionManager;
 
    /**
     * 增强(事务)的属性的配置
     *       isolation:DEFAULT  :事务的隔离级别.
     *       propagation              :事务的传播行为.
     *       read-only                        :false.不是只读
     *       timeout                          :-1
     *       no-rollback-for         :发生哪些异常不回滚
     *       rollback-for                    :发生哪些异常回滚事务
     * @return
     */
    @Bean
    public TransactionInterceptor txAdvice() {
           /*增强(事务)的属性的配置
            * <tx:attributes>
            * */
        NameMatchTransactionAttributeSource txAttributeS = new NameMatchTransactionAttributeSource();
           /*propagation="REQUIRED" , timeout=5 ;rollback-for=".. , .."配置*/
        RuleBasedTransactionAttribute requiredAttr = new RuleBasedTransactionAttribute();
        requiredAttr.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiredAttr.setTimeout(TX_METHOD_TIMEOUT);
        requiredAttr.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
           /*propagation="SUPPORTS" , readOnly="true"配置*/
        RuleBasedTransactionAttribute supportsAttr = new RuleBasedTransactionAttribute();
        supportsAttr.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
        supportsAttr.setReadOnly(true);
           /*
            注意:方法名称来自类匹配的到方法【save*, “*”表示匹配任意個字符】
             <tx:method .../>
            */
        Map<String , TransactionAttribute> txMethod = new HashMap<String , TransactionAttribute>();
        txMethod.put("add*" , requiredAttr);
        txMethod.put("save*" , requiredAttr);
        txMethod.put("del*" , requiredAttr);
        txMethod.put("mod*" , requiredAttr);
        txMethod.put("update*" , requiredAttr);
        txMethod.put("up*" , requiredAttr);
        txMethod.put("remove*" , requiredAttr);
        txMethod.put("set*" , requiredAttr);
        txMethod.put("change*" , requiredAttr);
        txMethod.put("logout*" , requiredAttr);
        txMethod.put("login*" , requiredAttr);
        txMethod.put("check*" , requiredAttr);
        txMethod.put("tiJiao*" , requiredAttr);
        txMethod.put("get*" , supportsAttr);
        txMethod.put("find*" , supportsAttr);
        txMethod.put("query*" , supportsAttr);
        txMethod.put("init*" , supportsAttr);
        txMethod.put("timing*" , requiredAttr);
        txMethod.put("execute*" , requiredAttr);
        txMethod.put("execute*" , requiredAttr);
        txMethod.put("send*" , requiredAttr);
        txMethod.put("batch*" , requiredAttr);
        txAttributeS.setNameMap(txMethod);
        TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager , txAttributeS);
        return txAdvice;
    }
 
    /**
     * AOP配置定义切面和切点的信息
     * @return
     */
    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut= new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut , txAdvice());
    }
 
}

————————————————
版权声明:本文为CSDN博主「衹染青春」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_40717107/article/details/99852981

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值