Springboot使用xml事务及相关说明

我想在springboot中采用模糊匹配的方式去配置事务,但是使用注解式的方式一直找不到实现的方式,后来找到一种通过xml文件的方式去实现模糊匹配的事务管理器方式。以下介绍一下这种方式的实现。

1,在resource文件夹下添加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">

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <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.example.txmanager.demo.spongebob.service.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" order="0"/>
    </aop:config>

    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

这里有一个坑:事务管理器,springboot会帮我们自动加载一个名为transactionManager的事务管理器。所以我们在该配置文件中再配置事务管理器的bean了。如果想自定义事务管理器,请先自行百度。

2.启用该配置

在入口程序中添加@ImportResource(“classpath:transaction.xml”)标签即可。
这里写图片描述

这样我们就实现了再springboot中实现模糊匹配的事务管理

3.知识点总结

1.@ImportResource 注解
该注解为springboot提供了springMvc中xml的配置方式。意味着我们完全可以把springMvc框架中xml配置文件中所需要的部分摘抄过来,最后通过@ImportResource注解引入实现。
2.
springboot它帮我们集成了很多东西,有很多的bean框架会帮我们自动导入,而我们只要直接引用就可以了,如上文的transactionManager对象。之前我是自定义了事务管理器txManager(如下),导致事务无效,不知道是dataSource引用写错的原因还是事务管理器冲突的原因导致配置事务无效,无法启用。

 <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" ></property>
    </bean>

猜你喜欢

转载自blog.csdn.net/u014296316/article/details/79750735