admin管理员组文章数量:1794759
spring mvc 给Controller添加事务
首先扫描配置要对:
原理:因为spring容器和spring-mvc是父子容器,spring容器会先加载,如果此时扫描了Controller,但未扫描到Service。spring事务配置文件还有上下文都是通过org.springframework.web.context.ContextLoaderListener加载的,而spring MVC的action是通过org.springframework.web.servlet.DispatcherServlet加载的 。web是先启动ContextLoaderListener后启动DispatcherServlet 在ContextLoaderListener加载的时候Controller并没在容器中,所以现在使用AOP添加事务或者扫描注解都是无用的。 结论:让spring扫描注册Service实现类,让MVC扫描注册Controller,此时spring父容器已经注册Service为Bean,此时事务可以得到正常配置。
扫描配置如下:spring-context.xml
<context:component-scan base-package="com.freecg.green007"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /></context:component-scan> spring-mvc.xml
<context:component-scan base-package="com.freecg.green007"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /></context:component-scan> spring父容器不扫描@Controller,MVC子容器不扫描@Service. 事务配置如下: spring-context.xml
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>------------------------------------------------------------------------------------------------------------------------------------------------------------------
一般而言,事务都是加在Service层的,也可以加在Controller层
在spring-framework-reference.pdf文档中有这样一段话:
<tx:annotation-driven/>
only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put
<tx:annotation-driven/>
in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.
这句话的意思是,<tx:annoation-driven/>只会查找和它在相同的应用上下文件中定义的bean上面的@Transactional注解,如果你把它放在Dispatcher的应用上下文中,它只检查控制器上的@Transactional注解,而不是你services上的@Transactional注解。
于是,我将事务配置定义在Spring MVC的应用上下文(spring-mvc.xml)中,
命名空间加红色部分
xmlns:tx="www.springframework/schema/tx" xsi:schemaLocation="www.springframework/schema/beans www.springframework/schema/beans/spring-beans-4.0.xsd www.springframework/schema/tx www.springframework/schema/tx/spring-tx.xsd
spring-mvc.xml加<tx:annotation-driven/>
将@Transactional(rollbackFor = { Exception.class })注解打在Controller上,
事务起就可以作用。
综上,在Spring MVC中,事务不仅可以加在Service层,同样也可以加在Controller层
参考:5880861.blog.51cto/5870861/1544168
blog.csdn/suyu_yuan/article/details/61190503
本文标签: 事务springMVCcontroller
版权声明:本文标题:spring mvc 给Controller添加事务 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686616636a86643.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论