天天看点

springMVC的事务不回滚

前言:今天在测试web管理端项目时,非常尴尬的是方法虽然用了事务注解,然而执行出错的情况下却没有进行事务回滚,也就是说@Transactional在springMVC的场景下失效了,通过调查和试验得出DispatcherServlet的context-dispatcher.xml和ContextLoaderListener的applicationContext.xml在进行context:component-scan标签设定时,需要互不影响。

最开始的时候,我在DispatcherServlet的context-dispatcher.xml配置以下内容

<context:component-scan base-package="com.honzh.spring"/>

在ContextLoaderListener的applicationContext.xml配置以下内容

在这样的情况下,假如存在以下方法

@Transactional

public void saveMember(Members members, HttpServletRequest request) throws Exception {

该方法内出现错误的时候,事务压根没有起到作用,修改以上两个文件到以下这样的效果

context-dispatcher.xml:

<context:component-scan base-package="com.honzh.spring">

 <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />

   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />

</context:component-scan>

applicationContext.xml:

 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />

然后再测试saveMember方法,出错的情况下事务回滚了,可以看到事务回滚的日志了

Transaction synchronization rolling back SqlSession

DEBUG 2015-02-05 17:30:11,074 org.springframework.jdbc.datasource.DataSourceTransactionManager: Releasing JDBC Connection

DEBUG 2015-02-05 17:30:11,074 org.springframework.jdbc.datasource.DataSourceUtils: Returning JDBC Connection to DataSource

ERROR 2015-02-05 17:30:11,075 com.honzh.spring.controller.MemberController:

java.lang.NullPointerException

可以看得出来:

有@Transactional注解的类需要通过父容器(applicationContext.xml)进行加载,而我原来的做法时,同时加载后,父容器和子容器发生冲突了,导致事务失效。