您的位置:首页 > 编程语言 > Java开发

Spring 配置事务管理无效(No Session found for current thread)原因及解决方案

2017-03-26 20:36 691 查看
       这里先说一下,真没有想到!Spring+SpringMVC 配置事务管理反而会无效!3天的冥思苦想,就是不明白连Spring事务那一块的源代码都看过了,真的没有配置错。
       然而,还是掉坑里面了!是Spring挖的坑!下面我就有娓娓道来:
1.配置出错了Spring没有任何提示,即使是Spring的包扫描配置根据不同的应用领域(Spring 事务和Spring MVC)会产生重复扫描的BUG!毫无提示!
2.错误提示:No Session found for current thread和真正的错误原因根本就是相差十万八千里,这里终于体会到了《Passengers》(太空旅客)中“Jim Preston”的体会了。一句话:完全不知道错哪了!

终于在角落里面发现了技术文章。现在转载一下。
以下转载自:http://blog.csdn.net/qq_32588349/article/details/52097943 ;

一般我们在spring的配置文件application.xml中对Service层代码配置事务管理,可以对Service的方法进行AOP增强或事务处理如事务回滚,但是遇到一个问题,在Controller类中调用Service层方法,配置的事务管理会失效,查询相关资料发现原因。其实Spring和SpringMVC俩个容器为父子关系,Spring为父容器,而SpringMVC为子容器。也就是说application.xml中应该负责扫描除@Controller的注解如@Service,而SpringMVC的配置文件应该只负责扫描@Controller,否则会产生重复扫描导致Spring容器中配置的事务失效。

因此正确的配置方式应该为:

Spring的配置文件:application.xml
<context:component-scan
base-package="org.bc.redis"
use-default-filters="true">

<!-- 排除含@Controller注解的类 -->

<context:exclude-filter
type="annotation"
expression="org.bc.redis.controller.UserController"/>

</context:component-scan> 
或者
<!-- 指定扫描的包,避开包含@Controller注解的包 -->

<context:component-scan
base-package="org.bc.redis.service"
use-default-filters="true">

 </context:component-scan> 
SpringMVC的配置文件:springmvc.xml
<!-- 只扫描含@Controller注解的包,避免重复扫描 -->

 <context:component-scan
base-package="org.bc.redis.controller"
use-default-filters="true">

 </context:component-scan>  

 最后 
经过测试,其实问题主要在于SpringMVC的配置文件扫包范围,Spring的配置文件就算也扫了@Controller注解,但是在SpringMVC会重新扫描一次,事务管理的Service只要没被重新扫描就不会出现事务失效问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息