---
title: "could not initialize proxy - the owning Session was closed"
author: "backbase"
date: "2010-07-15T08:41:01Z"
tags: []
categories: ["企业架构"]
slug: "could-not-initialize-proxy-the-owning-session-was-closed"
draft: false
lastmod: "2010-07-15T08:45:13Z"
id: 713079
url: "https://backbase.iteye.com/blog/713079"
---

问题：

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即可。参考如下的代码片段：

 

&lt;beans&gt;

    &lt;!-- The Hibernate interceptor, which takes care of opening and closing hibernate session around method calls. --&gt;

    &lt;bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor"&gt;

        &lt;property name="sessionFactory"&gt;

            &lt;ref bean="sessionFactory"/&gt;

        &lt;/property&gt;

    &lt;/bean&gt;

 

        &lt;bean id="quartzSchedulerFactory" lazy

.................

&lt;/beans&gt;

 

同时定义一个代理

 

      &lt;bean id="pointPaymentCouponIncomingSmsHandler" class="com.milesup.scheduler.handler.PointPaymentCouponIncomingSmsHandler"&gt;

                &lt;property name="telecomService"&gt;

                        &lt;ref bean="telecomService"/&gt;

                &lt;/property&gt;

             。。。。。。。。。。。。。。。。。

 

        &lt;/bean&gt;

        &lt;!-- A proxy with the hibernate interceptor wired in so it can access the persistent context --&gt;

    &lt;bean id="pointPaymentCouponIncomingSmsHandlerProxy" class="org.springframework.aop.framework.ProxyFactoryBean"&gt;

        &lt;property name="target"&gt;

            &lt;ref bean="pointPaymentCouponIncomingSmsHandler"/&gt;

        &lt;/property&gt;

        &lt;property name="interceptorNames"&gt;

            &lt;value&gt;hibernateInterceptor&lt;/value&gt;

        &lt;/property&gt;

    &lt;/bean&gt;

 

以上就是采用AOP技术，在运行时动态注入一个hibernateInterceptor即注入一个SessionFactory的方式解决这个问题。

 

具体参考附件