在整合Spring和SpringMVC的时候,我们需要通过Spring的位置文件applicatonContext.xml对代码逻辑层事务管理进行配置,即对Service层方法进行AOP增强或事务管理配置。但是奇怪的是,当Controller层使用了Service层的方法的时候配置的事务会失效。
其实Spring容器同SpringMVC容器存在着父子容器关系,Spring作为父容器,SpringMVC作为子容器。父容器是不允许访问子容器的,而子容器却可以访问父容器。故在配置Spring容器时候应该过滤掉对Controller层的扫描,而SpringMVC的配置文件应该只扫描Controller层,这样避免了重复扫描Spring容器中配置的事务,从而避免配置的事务失效。
Spring->SpirngContext.xml
<context:component-scan base-package="com.zxz.platform" use-default-filters="true"> //扫描时过滤掉Controller层 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> 或者扫描Service层的包 <context:component-scan base-package="com.zxz.platform.Service" use-default-filters="true"> </context:component-scan>SSpringMCV->dispatcher-servlet.xml
//只扫描Controller,避免对Service层事务的重复扫描 <context:component-scan base-package="com.zxz.platform.Controller" use-default-filters="true"> </context:component-scan>