spring mvc 给Controller添加事务
首先扫描配置要对:
原理:因为spring容器和spring-mvc是父子容器,spring容器会先加载,如果此时扫描了Controller,但未扫描到Service。
spring事务配置文件还有上下文都是通过org.springframework.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>
spring-mvc.xml
<context:exclude-filter type=annotation expression=org.springframework.stereotype.Service />
</context:component-scan>
spring父容器不扫描@Controller,MVC子容器不扫描@Service.
事务配置如下:
spring-context.xml
<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=http://www.springframework/schema/tx
xsi:schemaLocation=http://www.springframework/schema/beans
http://www.springframework/schema/beans/spring-beans-4.0.xsd
http://www.springframework/schema/tx
http://www.springframework/schema/tx/spring-tx.xsd
spring-mvc.xml加<tx:annotation-driven/>
将@Transactional(rollbackFor = { Exception.class })注解打在Controller上,
事务起就可以作用。
综上,在Spring MVC中,事务不仅可以加在Service层,同样也可以加在Controller层
参考:http://5880861.blog.51cto/5870861/1544168
http:///suyu_yuan/article/details/6119050
#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格
推荐阅读
留言与评论(共有 7 条评论) |
本站网友 开发者账号 | 11分钟前 发表 |
//5880861.blog.51cto/5870861/1544168 http | |
本站网友 7雄 | 30分钟前 发表 |
///suyu_yuan/article/details/6119050 | |
本站网友 金曼龙 | 21分钟前 发表 |
component-scan> spring父容器不扫描@Controller,MVC子容器不扫描@Service. 事务配置如下: spring-context.xml <tx | |
本站网友 金山和360 | 13分钟前 发表 |
and not your services. 这句话的意思是,<tx | |
本站网友 个人商业贷款计算器 | 18分钟前 发表 |
exclude-filter type=annotation expression=org.springframework.stereotype.Controller /> </context | |
本站网友 中间宿主 | 15分钟前 发表 |
但未扫描到Service |