SpringBoot中事务配置

SpringBoot中事务配置SpringBoot创建的项目,默认没有事务,还是需要自己配,真是日了狗。还有那个启动类,对,就是包含main方法的那个类一定要放在包的最外层,最外层,最外层,不然有很多坑。包括但不限于不能扫描到你配置的类,连接ES时自定义接口无法自动注入等等。1.Xml方式跟Spring中差不多两步骤①.在resources文件夹下创建xml文件。例如:transaction.xml别问我为…

大家好,又见面了,我是你们的朋友全栈君。

做个学习笔记。SpringBoot创建的项目由于不存在xml配置文件了,对于用惯Spring的xml配置事务犯了难,百度了下,大多文章都是用@Transactional对每一个方法或类手动添加任务,这样很麻烦,就自己摸索了下,实现了对指定切点事务的统一添加。有两种方式。PS:启动类,对,就是包含main方法的那个类一定要放在包的最外层,不然有很多坑。包括但不限于不能扫描到你配置的类,连接ES时自定义接口无法自动注入等等。

1.Xml方式

跟Spring中差不多两步骤

①.在resources文件夹下创建xml文件。例如:transaction.xml

SpringBoot中事务配置

 

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,这样写

SpringBoot中事务配置

要么方法名用dataSource,要么注解写成@Bean(“dataSource”)

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

SpringBoot中事务配置

两步完成,运行就完事儿了

2.注解方式

关于SpringBoot中的注解事务配置,网上一搜基本都是用@Transactional,那给每个类或方法配要给人累死了。

非常不推荐。所以想上面xml一样全局配置怎么办?同样是两步

①、配置事务类

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>

 

这里也不讲事务传播和隔离级别了,去百度吧,一大堆,也很简单。

如果你不嫌麻烦用@Aspect这个注解也行,具体百度Spring中怎么用

 

两种方式比较:

我还是比较推荐xml,一眼望去,清清楚楚。功能强大,不管是哪个类中哪个方法,只要你配置了事务就能生效

注解方式,即使controller层配置了事务,切点为* com.test.controller.*.*(..),事务也不生效,不知道为啥,@service层中的方法正常配置就有效。有坑。当然,对于@controller层中也要做事务,可以用@Transactional,不过一般人不需要controller开启事务吧

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/136816.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • Qmake VS Cmake

    Qmake VS Cmake用cmake构建Qt工程(对比qmake进行学习)cmakevsqmakeqmake是为Qt量身打造的,使用起来非常方便cmake使用上不如qmake简单直接,但复杂换来的是强大的功能内置的out-ofsource构建。(目前QtCreator为qmake也默认启用了该功能。参考:浅谈qmake之sha

  • hz的单位换算速度_hz与w怎么换算

    hz的单位换算速度_hz与w怎么换算物质在1秒内完成周期性变化的次数叫做频率,常用f表示。物理中频率的单位是赫兹(Hz),简称赫,也常用千赫(kHz)或兆赫(MHz)或GHz做单位,单位符号为Hz。.hz是一个频率的单位,它表示物体在一秒钟之内振动一次,它的频率就是1hz。k代表千,khz即千赫芝;m代表兆,mkhz即兆赫芝;还有一个g代表京,它们都是英美换算单.20kHz等于20000Hz。具体换算过程如下。千赫兹(KHz)和赫兹…

  • KDD2018《Adversarial Attacks on Neural Networks for Graph Data》 论文详解「建议收藏」

    KDD2018《Adversarial Attacks on Neural Networks for Graph Data》 论文详解「建议收藏」论文链接:https://arxiv.org/pdf/1805.07984.pdfAbstract本文介绍了第一个在属性图上进行对抗攻击的研究,特别关注利用图卷积的思想模型。除了在测试阶段进行攻击,本文进行了更具挑战的poisoningattack(聚焦于机器学习模型的训练阶段)类别。在考虑实例间依赖关系的情况下,针对节点特征和图结构进行对抗扰动(adversarialperturbation)。通过保证重要的数据特征保证扰动是不可见的(unnoticeable)。为了解决底层的离散域(disc

  • JVM-内存结构「建议收藏」

    JVM-内存结构「建议收藏」分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.netJVM在执行程序的过程中会将内存划分为不同的数据区域,请看下图。如果理解了上图,JVM的内存结构基本上掌握了一半。从图中可以得到如下信息。第一,JVM分为五个区域:虚拟机栈、本地方法栈、方法区、堆、程序计数器。第二,JVM五个区中虚拟机栈、本地方法栈、程序计数器为线程私有,方法区和堆为线程共享区。图中已经用颜色区分。第三,JVM不同区域占用的内

  • 计算机发展史上代表性的人物,计算机发展史最具影响力人物「建议收藏」

    计算机发展史上代表性的人物,计算机发展史最具影响力人物「建议收藏」1.冯·诺依曼 1903-1957开创了现代计算机理论,其体系结构沿用至今,而且他早在40年代就已预见到计算机建模和仿真技术对当代计算机将产生的意义深远的影响2.蒂姆·伯纳斯·李  1955-互联网之父蒂姆·伯纳斯·李是万维网的发明人,也是万维网联盟(World Wide Web Consortium)的发起人。1990年,他在日内瓦的欧洲粒子物理实验室里开发出了世界上第一个网页浏览器。3.罗伯特…

    2022年10月18日
  • 苹果关闭自动更新_iOS屏蔽更新不用描述文件,苹果官方:安排![通俗易懂]

    他来了!他来了!我们可以看到iOS13.6系统测试版在设置里添加了一个关闭自动下载和自动安装的按钮。左:iOS13.5.1右:iOS13.6苹果手机的iOS系统小版本更新不断,老是自动下载更新包,让人感到被强迫升级,即使苹果公司的出发点是好的,“这是为你们好,最新系统更安全”。然而大多数用户都认为没必要经常升级系统,不升级就不会遇到系统Bug,经常升级难免会遇到。有一种…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号