一般我們在Spring的配置文件application.xml中對Service層代碼配置事務管理,可以對Service的方法進行AOP增強或事務處理如事務回滾,但是遇到一個問題,在Controller類中調用Service層方法,配置的事務管理會失效,查詢相關資料發現原因。其實Spring和SpringMVC倆個容器為父子關係,Spring為父容器,而SpringMVC為子容器。也就是說application.xml中應該負責掃描除@Controller的註解如@Service,而SpringMVC的配置文件應該只負責掃描@Controller,否則會產生重複掃描導致Spring容器中配置的事務失效。
因此正確的配置方式應該為:
Spring的配置文件:application.xml
<context:component-scan base-package="org.bc.redis" use-default-filters="true"> <!-- 排除含@Controller註解的類--> <context:exclude-filter type="annotation" expression="org.bc.redis.controller.UserController"/> </context:component-scan>
或者
<!-- 指定掃描的包,避開包含@Controller註解的包--> <context:component-scan base-package="org.bc.redis.service" use-default-filters="true"> </context:component-scan>
SpringMVC的配置文件:springmvc.xml
<!-- 只掃描含@Controller註解的包,避免重複掃描--> <context:component-scan base-package="org.bc.redis.controller" use-default-filters="true"> </context:component-scan>
最後
經過測試,其實問題主要在於SpringMVC的配置文件掃包範圍,Spring的配置文件就算也掃了@Controller註解,但是在SpringMVC會重新掃描一次,事務管理的Service只要沒被重新掃描就不會出現事務失效問題。
總結
以上就是本文關於Spring+SpringMVC配置事務管理無效原因及解決辦法詳解的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!