spring mvc 给Controller添加事务
来源:互联网 发布:webrtc 源码介绍 编辑:程序博客网 时间:2024/06/05 21:06
首先扫描配置要对:
原理:因为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
spring-mvc.xml
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
spring父容器不扫描@Controller,MVC子容器不扫描@Service.
事务配置如下:
spring-context.xml
<property name="dataSource" ref="dataSource" />
一般而言,事务都是加在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="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
spring-mvc.xml加<tx:annotation-driven/>
将@Transactional(rollbackFor = { Exception.class})注解打在Controller上,
事务起就可以作用。
参考:http://5880861.blog.51cto.com/5870861/1544168
http://blog.csdn.net/suyu_yuan/article/details/61190503
- spring mvc 给Controller添加事务
- spring mvc 给Controller添加事务不成功的原因
- spring mvc 给Controller添加事务不成功的原因
- spring mvc 给Controller添加事务不成功的原因
- spring mvc 给action添加事务不成功的原因
- spring mvc 给action添加事务不成功的原因
- spring mvc 给action添加事务不成功的原因
- 在Spring MVC中,事务可以加在Controller层
- 在Spring MVC中,事务可以加在Controller层
- 在Spring MVC中,事务可以加在Controller层
- 在Spring MVC中,事务可以加在Controller层
- 在Spring MVC中,事务可以加在Controller层
- Spring MVC中,事务是否可以加在Controller层
- Spring MVC中Controller如何将数据返回给页面
- spring MVC -controller
- spring mvc的Controller
- Spring MVC Controller
- Spring MVC中的Controller
- android中的无线通信蓝牙
- C/C++中的static关键字的易错点
- exercise5
- C# ASP.NET 解决方案开发微信公众号
- Discuz手机触屏版的帖子中图片无法放大查看
- spring mvc 给Controller添加事务
- Tomcat启动时加载数据到缓存--Web.xml里listener的加载顺序,优先初始化Spring IOC容器
- 关于android webview 的那些坑
- ArrayDeque
- 面向对象中的原型链
- 1133: 单词个数统计
- js 回调
- 基于OpenXES的XES反序列化源码示例
- 用NPOI操作EXCEL--画线