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,此时事务可以得到正常配置。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章