Spring事務 的理解


在使用Spring的時候,配置文件中我們經常看到 annotation-driven 這樣的注解,其含義就是支持注解,一般根據前綴 tx、mvc 等也能很直白的理解出來分別的作用。

<tx:annotation-driven/> 就是支持事務注解的(@Transactional) 。

<mvc:annotation-driven> 就是支持mvc注解(Controller中可以使用MVC的各種注解)。

<tx:annotation-driven/>  會有一個屬性來指定使用哪個事務管理器,如:

<tx:annotation-driven transaction-manager="txManager" />//txManager就是指定的事務管理器

這樣逐層引用下去,所以我們使用@Transactionl 注解可以控制事務就通俗易懂了。

另外要提一下的就是 Spring 是使用 aop 通過 asm 操作Java字節碼的方式來實現對方法的前后事務管理的。

那我們是否就可以在程序中所有被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://my.oschina.net/wuminghai/blog/760033


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM