Spring MVC中,事务是否可以加在Controller层

 一般而言,事务都是加在Service层的,但是爱钻牛角尖的我时常想:事务加在Controller层可不可以。我一直试图证明事务不止可以加在Service层,还可以加在Controller层,但是没有找到有力的论据来支持我这个想法,搞得我一度认为事务只能加在Service层,直到我读过spring官方文档并实践之后,我知道我的想法是对的。

    在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的应用上下文(*-servlet.xml)中,将@Transactional注解打在Controller上,终于事务起作用了。

    综上,在Spring MVC中,事务不仅可以加在Service层,同样也可以加在Controller层(虽然不推荐这么做,但至少满足了我的好奇心,(*^__^*) 嘻嘻……)。

 

注意: Controller层只支持 @Transactional 注解式事务!

 

原文:http://blog.csdn.net/mmm333zzz/article/details/45288061

posted @ 2016-07-13 14:48  但行好事-莫问前程  阅读(14028)  评论(0编辑  收藏  举报