1. 程式人生 > >關於Spring事務的理解(Controller可以使用@Transactional)

關於Spring事務的理解(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/>的使用。