javascript
Spring3MVC+Mybatis3.1框架下的事务
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
最近做一個(gè)項(xiàng)目,項(xiàng)目的框架采用是Spring3MVC+MyBatis3.1。可是在開發(fā)過程中發(fā)現(xiàn)配置的事務(wù)不管用。
出現(xiàn)這個(gè)問題的現(xiàn)象是用Junit調(diào)試事務(wù)管用,而部署到Tomcat中就不管用了。先看看事務(wù)的配置:
<!--proxy-target-class="true"強(qiáng)制使用cglib代理 ? 如果為false則spring會自動選擇-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 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>
采用以下兩種方法調(diào)試:
一、Debug視圖
?1、Junit下的
發(fā)現(xiàn)配置事務(wù)的AOP已經(jīng)包進(jìn)來了。再看看Tomcat中運(yùn)行的Debug截圖:
顯然AOP沒有被包進(jìn)來。
二、Log4J的記錄:
Junit下的記錄:
Spring托管了事務(wù)。
Tomcat運(yùn)行時(shí)的記錄:
Spring沒有托管事務(wù)。
從以上兩種方法的調(diào)試說明了,事務(wù)的配置是正確的,只是在部署到Tomcat中,沒有被托管。為什么會在Junit的時(shí)候就可以呢?得看看Junit的配置:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
@ContextConfiguration("classpath:applicationContext.xml")
這是Junit加載Spring容器的注解。ContextConfiguration會把a(bǔ)pplicationContext.xml的Bean都加載了,這就說明Tomcat在運(yùn)行時(shí)沒有將applicationContext.xml的Bean加載進(jìn)來。問了前輩,前輩的回話是這樣的:
切面配置在了root applicationContext的bean上了,而spring mvc會根據(jù)xxx-servelt.xml生成一個(gè)自己的applicationContext,他的父applicationContext為root applicatonContext,當(dāng)mvc有自己的bean時(shí)便不再去向父context要bean,導(dǎo)致聲明事務(wù)無效。
看了前輩的這個(gè)郵件,我將applicationContext.xml中配置事務(wù)的AOP復(fù)制到XXX-servlet.xml中。再調(diào)試,Tomcat中運(yùn)行項(xiàng)目事務(wù)被Spring托管了,也就是問題解決了!!
問題解決后查看了Spring3.1的Docs發(fā)現(xiàn)了以下的內(nèi)容:
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.
轉(zhuǎn)載于:https://my.oschina.net/xuqiang/blog/97633
總結(jié)
以上是生活随笔為你收集整理的Spring3MVC+Mybatis3.1框架下的事务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 寒冬日,找阳光
- 下一篇: Json-lib使用——JSONObje