springMVC事务配置步骤和规范
猿类始祖 2017-05-18 09:53:00 springMVC存在事务处理的逻辑必须在Service层定义,在其他层定义如果异常被捕获则会出现事务不回滚现象。
以下是springMVC事务的配置过程:
一、在applicationContext.xml中确认有以下的XML Schema
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
二、在applicationContext.xml中添加 transaction Manager
<!-- Spring Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
三、在applicationContext.xml中添加事务支持
<!-- enable transaction annotation support -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
PS.proxy-target-class=true表明自动生成代理类,Service无需定义接口。
如果proxy-target-class=true需添加以下配置支持
<aop:aspectj-autoproxy />
四、在applicationContext.xml中配置事务的隔离机制
也可以在注解中配置,但是我们推荐在xml中配置,可读性更高
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- 如果不指定rollback-for默认为RuntimeException,抛出自定义异常可能导致事务不回滚。建议统一指定为Exception -->
<tx:method name="update*" rollback-for="RuntimeException" propagation="REQUIRES_NEW"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* x.y.service.FooService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
五、SpringMVC事务不回滚情况处理
造成SpringMVC事务不回滚的情况大多是因为springMVC子容器加载了未添加事务处理的Service造成,处理方法是在SpringMVC的XML配置(spring-mvc.xml)中排除掉Service注解(Service层必须使用@Service注解)
<context:component-scan base-package="com.uns" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>