天天看點

關于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/>的使用。