一般而言,事務都是加在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