Spring3MVC+Mybatis3.1框架下的事务

最近作一个项目,项目的框架采用是Spring3MVC+MyBatis3.1。但是在开发过程当中发现配置的事务无论用。 web

出现这个问题的现象是用Junit调试事务管用,而部署到Tomcat中就无论用了。先看看事务的配置: spring

<!--proxy-target-class="true"强制使用cglib代理   若是为false则spring会自动选择-->
<aop:aspectj-autoproxy proxy-target-class="true"/> express

<!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="save*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>


<aop:config>
<aop:pointcut expression="execution(public * com.luyou.platform.service.impl.*Impl.*(..))" id="pointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
mvc


采用如下两种方法调试: app

1、Debug视图 框架

 一、Junit下的 spa

发现配置事务的AOP已经包进来了。再看看Tomcat中运行的Debug截图: 代理

显然AOP没有被包进来。 调试


2、Log4J的记录: orm

Junit下的记录:

Spring托管了事务。

Tomcat运行时的记录:

Spring没有托管事务。


从以上两种方法的调试说明了,事务的配置是正确的,只是在部署到Tomcat中,没有被托管。为何会在Junit的时候就能够呢?得看看Junit的配置:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
@ContextConfiguration("classpath:applicationContext.xml")

这是Junit加载Spring容器的注解。ContextConfiguration会把applicationContext.xml的Bean都加载了,这就说明Tomcat在运行时没有将applicationContext.xml的Bean加载进来。问了前辈,前辈的回话是这样的:

切面配置在了root applicationContext的bean上了,而spring mvc会根据xxx-servelt.xml生成一个本身的applicationContext,他的父applicationContext为root applicatonContext,当mvc有本身的bean时便再也不去向父context要bean,致使声明事务无效。

看了前辈的这个邮件,我将applicationContext.xml中配置事务的AOP复制到XXX-servlet.xml中。再调试,Tomcat中运行项目事务被Spring托管了,也就是问题解决了!!

问题解决后查看了Spring3.1的Docs发现了如下的内容:

These inherited beans can be overridden in the servlet-specific scope, and you can define new scope-specific beans local to a given Servlet instance.
Context hierarchy in Spring Web MVC Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.

相关文章
相关标签/搜索