Spring 事务处理

Spring 默认执行事务回滚:当开启事务的类中对数据库的操作的异常没有任何处理时,才会主动触发事务回滚。

而很多时候业务都需要对抛出的异常进行处理,所以如果try,catch了操作数据库的方法,事务是不会主动回滚的,这时就需要手动去进行事务回滚

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚,对于捕获的异常

Spring AOP 配置文件,需要在<list>中配置要开启事务的类

<?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
            <list>
                <idref bean="baseService" />
                <idref bean="asyncServiceImpl" />
                <idref bean="transactionService" />
                <idref bean="yhxxzhcxService" />
            </list>
        </property>
        <property name="interceptorNames">
            <list>
                <idref bean="transactionInterceptor" />
            </list>
        </property>
    </bean>

    <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager" ref="transactionManager" />
        <property name="transactionAttributes">
            <props>
                <prop key="get*">PROPAGATION_SUPPORTS,-Exception,readOnly</prop>
                <prop key="find*">PROPAGATION_SUPPORTS,-Exception,readOnly</prop>
                <prop key="search*">PROPAGATION_SUPPORTS,-Exception,readOnly</prop>
                <prop key="query*">PROPAGATION_SUPPORTS,-Exception,readOnly</prop>
                <prop key="count*">PROPAGATION_SUPPORTS,-Exception,readOnly</prop>
                <prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
            </props>
        </property>
    </bean>

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

</beans>
原文地址:https://www.cnblogs.com/Yiran583/p/4934033.html