spring boot 事物配置简单化

spring boot 事物配置简单化

在没有使用spring booot之前我都是使用xml进行事物的配置,我们只需要在xml中配置好了之后在编码的过程中就不在需要关注事物的管理,很是方便。

在使用spring boot 之后,发现需要在进行事物管理的方法上添加注解@Transactional,或者懒的话直接在类上面添加该注解,使得所有的方法都进行事物的管理,很是麻烦。 就想能不能像xml中那样进行配置,一次配置,不再考虑。

经过查找发现好像并没有注解可以实现(如果你找到了,欢迎一起交流),还得在xml中进行配置,然后使用@ImportResource("classpath:transactionManager.xml")引入该xml的配置。 transactionManager.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="cfPointCut"
            expression="execution(* com..*Controller.*(..)) 
            || execution(* com..*ServiceImp.*(..)) 
            || execution(* com..*Service.*(..)) 
            || execution(* com..*Dao.*(..))" ></aop:pointcut>
        <aop:advisor pointcut-ref="cfPointCut" advice-ref="cftxAdvice" ></aop:advisor>
    </aop:config>

</beans>

参考自 http://stackoverflow.com/questions/29333942/spring-boot-with-transactional-configuration

猜你喜欢

转载自my.oschina.net/u/2523704/blog/906749