spring mvc 給Controller添加事務不成功的原因

掃描配置如下:
spring-context.xml

<context:component-scan base-package="com.freecg.green007">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

spring-mvc.xml

<context:component-scan base-package="com.freecg.green007"> 
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

spring父容器不掃描@Controller,MVC子容器不掃描@Service.

事務配置如下:
spring-context.xml

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

因爲spring容器和spring-mvc是父子容器,spring容器會先加載,如果此時掃描了Controller,但未掃描到Service。
spring事務配置文件還有上下文都是通過org.springframework.web.context.ContextLoaderListener加載的,而spring MVC的action是通過org.springframework.web.servlet.DispatcherServlet加載的 。
web是先啓動ContextLoaderListener後啓動DispatcherServlet 在ContextLoaderListener加載的時候action並沒在容器中,所以現在使用AOP添加事務或者掃描註解都是無用的。

結論:讓spring掃描註冊Service實現類,讓MVC掃描註冊Controller,此時spring父容器已經註冊Service爲Bean,此時事務可以得到正常配置。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章