SSM整合事务失效

在整合SSM后测试事务,发现添加到service层的事务没有生效,后面参考博文,发现是是扫描包的时候,springmvc配置文件里也扫描了,然后spring配置文件中也扫描了,下面参考博文说springmvc扫描后的包事务会失效,验证是有这个影响。

只在SpringMVC中配置包扫描

测试只在SpringMVC中包扫描,现将Spring包扫描注释掉、发现默认事务失效。

(1)spring核心配置文件applicationCotext.xml注释掉包扫描

1     <!-- 开启包扫描 -->
2     <!--<context:component-scan base-package="com.boe.web"/>-->
3     <!--<context:component-scan base-package="com.boe.service"/>-->
4     <!--<context:component-scan base-package="com.boe.dao"/>-->

(2)springmvc核心配置文件进行包扫描

1      <context:component-scan base-package="com.boe.dao"></context:component-scan>
2      <context:component-scan base-package="com.boe.service"></context:component-scan>
3      <context:component-scan base-package="com.boe.web"></context:component-scan>

(3)service层添加User方法手动造一个运行期异常,但是异常出现是在添加用户之后,其他代码省略。

1     @Override
2     @Transactional(propagation = Propagation.REQUIRED)
3     public int registUser(User user) {
4         int addResult = userMapper.addUser(user);
5         int i=1/0;
6         return addResult;
7     }

(4)正常启动tomcat服务器后,浏览器端访问服务器添加用户,执行报错,但是数据却正常插入,事务没有生效。

浏览器端报错提示,这里使用restful风格提交参数,参数为'youngchaolin'和'88':

数据库正常插入:

 

可以看出来虽然在service层方法上添加了事务传播属性,但是事务不会滚。

只在Spring中配置包扫描

(1)与上面类似,这里配置包扫描换做全在applicationContext.xml文件中进行,将springmvc中的注释掉,继续测试。由于springmvc配置文件没有包扫描,这样跟访问相关的注解@RequestMapping没有生效,使用浏览器无法添加,这里使用junit测试。获取web层controller,直接调用它身上的regist方法添加用户,添加用户需要调用service层因此可以看出影响。

1     @Test
2     public void test06(){
3         FirstController controller=context.getBean("userController",FirstController.class);
4         User user=new User();
5         user.setName("铁扇公主");
6         user.setAge(200);
7         String s = controller.regist(user);
8     }

(2)service层不变,执行依然报错。

(3)数据库查看,发现事务生效,铁扇公主,200岁的数据没有插入。

 

 这里说明配置在spring核心配置文件中的包扫描才有效果,但是网页却无法访问,这是因为web层包扫描配置在了spring核心配置文件里,修改为web层包扫描配置在springmvc中,做一次测试。

springmvc只扫描web层包

(1)springmvc包扫描配置

1      <!--开启包扫描-->
2      <!--<context:component-scan base-package="com.boe.dao"></context:component-scan>-->
3      <!--<context:component-scan base-package="com.boe.service"></context:component-scan>-->
4      <context:component-scan base-package="com.boe.web"></context:component-scan>

(2)spring包扫描文件

1     <!-- 开启包扫描 -->
2     <!--<context:component-scan base-package="com.boe.web"/>-->
3     <context:component-scan base-package="com.boe.service"/>
4     <context:component-scan base-package="com.boe.dao"/>

(3)正常启动tomcat服务器后,发现可以访问服务器但返回服务器异常。

(4)查看数据库端数据发现没有插入,事务生效,messi+99的数据没有插入。 

结论

spring配置文件applicationContext.xml中配置了事务,如果想事务生效,需要事务所在的包放在spring配置文件中进行扫描,web包一般会使用springmvc注解,因此需在springmvc配置文件中进行包扫描。 

参考博文:

(1)https://www.cnblogs.com/fanzuojia/p/10470182.html

(2)https://www.cnblogs.com/youngchaolin/p/10628776.html

原文地址:https://www.cnblogs.com/youngchaolin/p/11648289.html