问题:
could not initialize proxy - the owning Session was closed
参考如下的帖子:http://lz726.iteye.com/blog/116616
问题的描述:
在使用quartz定时扫描处理客户上行短信的方法中,调用自己定义的一个Service层中的一个load一个实体对象如Member
member = load(1)返回到该方法使用,
由于是采用load方法,所以返回的是真正实体对象的一个代理,而不是真正的实体对象。返回后,
由于调用自己定义的一个Service层后事务所对应的SessionFactory就已经关闭了,
然后再重新回到自己定义的方法中的时候,Service中SessionFactory已经关闭当然其对应的session也已经关闭,此时我们在去调用
我们load过来的对象的某个方法的时候如member.getName(),此时SessionFactory已经关闭,所以就会报
could not initialize proxy - the owning Session was closed 这个异常,
解决办法是什么呢?
在我们的applicationContext-quartz.xml文件中动态注入一个SessionFactory即可。参考如下的代码片段:
<beans>
<!-- The Hibernate interceptor, which takes care of opening and closing hibernate session around method calls. -->
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="quartzSchedulerFactory" lazy
.................
</beans>
同时定义一个代理
<bean id="pointPaymentCouponIncomingSmsHandler" class="com.milesup.scheduler.handler.PointPaymentCouponIncomingSmsHandler">
<property name="telecomService">
<ref bean="telecomService"/>
</property>
。。。。。。。。。。。。。。。。。
</bean>
<!-- A proxy with the hibernate interceptor wired in so it can access the persistent context -->
<bean id="pointPaymentCouponIncomingSmsHandlerProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref bean="pointPaymentCouponIncomingSmsHandler"/>
</property>
<property name="interceptorNames">
<value>hibernateInterceptor</value>
</property>
</bean>
以上就是采用AOP技术,在运行时动态注入一个hibernateInterceptor即注入一个SessionFactory的方式解决这个问题。
具体参考附件