找不到Hibernate session 是springMVC+freemarker 搭建项目中一个很容易出错的地方。
在配置applicationContext的时候,很容易就配置成这样了
<!-- 扫描注解Bean -->
<context:component-scan base-package="com.neven.zsgc.dao" />
<context:component-scan base-package="com.neven.zsgc.service">
</context:component-scan>
<context:component-scan base-package="com.neven.zsgc.controller">
</context:component-scan>
<context:component-scan base-package="com.neven.zsgc.dao" />
<context:component-scan base-package="com.neven.zsgc.service">
</context:component-scan>
<context:component-scan base-package="com.neven.zsgc.controller">
</context:component-scan>
如果使用AOP配置事物, 这时就留下一个陷阱。
此时如果使用了AOP配置Hibernate事物,
会导致找不到Hibernate session异常,其过程如下:
1,页面调用Controller
2, Controller 找到service 直接调用Dao
3,但是Dao不是运行在一个事物中,无法加载Session
正确的配置应该如下:
在applicationContext.xml中仅仅配置DAO和Service
<context:component-scan base-package="com.neven.zsgc.dao" /> <context:component-scan base-package="com.neven.zsgc.service"/>
mvc配置(我的为dispatcher.xml)中配置Controller,而且使用
context:exclude-filter节点配置告诉spring不要扫描Service
<context:component-scan base-package="com.neven.zsgc.controller" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>
这样基本就可以解决问题。
至于原因这里说了点: