javascript
关于Spring事务tx:annotation-driven/的理解(Controller可以使用@Transactional)
在使用SpringMvc的時候,配置文件中我們經??吹?annotation-driven 這樣的注解,其含義就是支持注解,一般根據前綴 tx、mvc 等也能很直白的理解出來分別的作用。<tx:annotation-driven/> 就是支持事務注解的(@Transactional) 、<mvc:annotation-driven> 就是支持mvc注解的,說白了就是使Controller中可以使用MVC的各種注解。
? ? 首先,<tx:annotation-driven/> ?會有一個屬性來指定使用哪個事務管理器,如:<tx:annotation-driven transaction-manager="transactionManager" />。然后事務管理器?transactionManager 會引用 dataSource (如果我們使用JPA或Hibernate,也需要指定一個 entityManagerFactory?),dataSouce 肯定就是直接對數據庫的了。
? ? 這樣逐層引用下去,所以我們使用@Transactionl 注解可以控制事務就通俗易懂了。另外要提一下的就是 spring 是使用 aop 通過 asm 操作java字節碼的方式來實現對方法的前后事務管理的。
? ? 說到這里,已經有了對?<tx:annotation-driven/> 的簡單理解,那我們是否就可以在程序中所有被spring管理的類上都可以使用@Transactional注解了呢,在Service上可以使用 @Transactional 注解這個是肯定的了,那總有些人也想弄明白能否在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 的應用上下文中,它只檢查控制器(Controller)上的@Transactional注解,而不是你services上的 @Transactional注解。
? ? 所以,可以確定的是我們是可以在Controller上使用事務注解的,但是我們不推薦這樣做(本人也從來沒有這樣做過),這里只是為了說明spring對<tx:annotation-driven/>的使用。
轉載于:https://www.cnblogs.com/liaojie970/p/5153866.html
總結
以上是生活随笔為你收集整理的关于Spring事务tx:annotation-driven/的理解(Controller可以使用@Transactional)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Solr in Action 翻译完成情
- 下一篇: app.config 配置的一种用法