前言:今天在測試web管理端項目時,非常尴尬的是方法雖然用了事務注解,然而執行出錯的情況下卻沒有進行事務復原,也就是說@Transactional在springMVC的場景下失效了,通過調查和試驗得出DispatcherServlet的context-dispatcher.xml和ContextLoaderListener的applicationContext.xml在進行context:component-scan标簽設定時,需要互不影響。
最開始的時候,我在DispatcherServlet的context-dispatcher.xml配置以下内容
<context:component-scan base-package="com.honzh.spring"/>
在ContextLoaderListener的applicationContext.xml配置以下内容
在這樣的情況下,假如存在以下方法
@Transactional
public void saveMember(Members members, HttpServletRequest request) throws Exception {
該方法内出現錯誤的時候,事務壓根沒有起到作用,修改以上兩個檔案到以下這樣的效果
context-dispatcher.xml:
<context:component-scan base-package="com.honzh.spring">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
applicationContext.xml:
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
然後再測試saveMember方法,出錯的情況下事務復原了,可以看到事務復原的日志了
Transaction synchronization rolling back SqlSession
DEBUG 2015-02-05 17:30:11,074 org.springframework.jdbc.datasource.DataSourceTransactionManager: Releasing JDBC Connection
DEBUG 2015-02-05 17:30:11,074 org.springframework.jdbc.datasource.DataSourceUtils: Returning JDBC Connection to DataSource
ERROR 2015-02-05 17:30:11,075 com.honzh.spring.controller.MemberController:
java.lang.NullPointerException
可以看得出來:
有@Transactional注解的類需要通過父容器(applicationContext.xml)進行加載,而我原來的做法時,同時加載後,父容器和子容器發生沖突了,導緻事務失效。