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

Spring3 + Hibernate4 配置 No Session found for current thread问题的解决

2013-01-22 13:21 627 查看
在使用Spring mvc + Spring + Hibernate4配置的时候,总是出现 No Session found for current thread,仔细检查applicationContext.xml和dispacter-servlet.xml文件,注解、事务配置都没有问题,纠结好久。

网上搜了很多方法,都不能解决。

有说加上<prop
key="hibernate.current_session_context_class">thread</prop>的配置。有说hibernate4要加上的是<prop
key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>,经过测试,都不能解决。

看了http://blog.csdn.net/qq445422083/article/details/8160387帖子之后,觉得说的有道理,还是事务没有装配。

试着把dispacter-servlet.xml中的内容合并到[b]applicationContext.xml中,采用一个配置文件(当然web.xml也要做相应修改),发现并没有报错,问题解决。[/b]

[b]
但是自己还是喜欢使用两个配置文件,这样结构更清晰。
[/b]
[b]
分析为什么合并到一起就没问题呢,原来[b]spring的context是父子容器,所以会产生冲突,Controller会首先被扫描装配,而此时的Service还没有进行事务的配置,获得的将是原样的Service(没有经过事务装配,故而没有事务处理能力) ,最后才是applicationContext.xml中的扫描设备进行事务处理。
[/b][/b]
[b]这样就好办了,让两个配置文件各干各的事就可以了。[/b]

1 、在Spring主容器中(applicationContext.xml),用<context:exclude-filter/>将Controller的注解过滤掉,不扫描装配它。

[html] view
plaincopy

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

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

</context:component-scan>

2 而在springMVC配置文件中(dispatcher-servlet.xml)将Service和Dao的注解给[b]过滤
,只扫描装配Controller。[/b]

[html] view
plaincopy

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

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

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

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

</context:component-scan>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐