美文网首页
springboot配置事务

springboot配置事务

作者: 凉风拂面秋挽月 | 来源:发表于2020-04-24 00:12 被阅读0次

阿里面试被问到了,当时没想起来@Transactional,哎。现在查了一下,发现有3种配置方式,那就在这里记录下吧。

Xml方式

在resources文件夹下创建xml文件。例如:transaction.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="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.test.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" order="0"/>
    </aop:config>
</beans>

dataSource是直接拿来用的,所以你在加载DataSource对象时候必须命名为dataSource。比如我用的连接池是阿里的druid,这样写


image.png

在启动类上添加@ImportResource注解,例如:@ImportResource("classpath:transaction.xml")

image.png

注解式

配置事务类

package com.test.aop;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
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;
import com.test.domain.DqeProfileDefine;
@Configuration
public class TxAnoConfig {
    @Autowired
    private DataSource dataSource;  
    @Bean("txManager")
    public DataSourceTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource);
    }
    /*事务拦截器*/
    @Bean("txAdvice")
    public  TransactionInterceptor txAdvice(DataSourceTransactionManager txManager){    
        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 new TransactionInterceptor(txManager ,source) ;
    }
    /**切面拦截规则 参数会自动从容器中注入*/
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor(TransactionInterceptor txAdvice){
        DefaultPointcutAdvisor pointcutAdvisor = new DefaultPointcutAdvisor();
        pointcutAdvisor.setAdvice(txAdvice);
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution (* com.test.service.*.*(..))");
       pointcutAdvisor.setPointcut(pointcut);
       return pointcutAdvisor;
    }
}

在pom.xml中添加依赖

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
</dependency>

然后在需要配置事务的方法上设置切点。* com.test.controller..(..)

@Transactional

最简单的一种,没有上面两种可以做全局的事务这么强大,直接将该注解家在方法上即可开启事务。

@Transactional
@Override
public void save() {
   User user = new User("xuxiao");
    userMapper.insertSelective(user);
    if (true) {
        throw new RuntimeException("抛异常了");
    }
}

相关文章

网友评论

      本文标题:springboot配置事务

      本文链接:https://www.haomeiwen.com/subject/nhutwhtx.html