日期:2014-05-16  浏览次数:20389 次

Spring的findBean和sessionBind
现在的项目是Jsf+Hibernate+Spring+Birt(报表)构成的.但由于Birt没有纳入Jsf的管理因而当遇到Hibernate的延迟加载时会报session关闭错误.解决方法是(自己的理解,说的不定对):

//findBean是Spring提供的方法,通过Name获得配置文件的Bean.由于Spring在项目初始化时就已经注入好,因而拿来使用即可
public Object findBean(String beanname, ServletContext context) {
       ApplicationContext appctx = WebApplicationContextUtils
              .getRequiredWebApplicationContext(context);
       return appctx.getBean(beanname);
    }


//sessinBindThread:这是问题解决的关键由于没纳入Jsf管理,Spring是不会自动在请求时生成Session并绑定其上的,而以下就是手动绑定Session.

public void sessionBindThread(ServletContext context) throws Exception {
       SessionFactory factory = (SessionFactory) findBean(
              "FactoryName", context);
       Session sInfo = SessionFactoryUtils.getSession(factory, true);    
       if(TransactionSynchronizationManager.getResource(factory) == null){
           TransactionSynchronizationManager
               .bindResource(factory,new SessionHolder(sInfo));
       }
    }


//请求之后要解绑!!

public void sessionOutThread(ServletContext context) throws Exception {
       SessionFactory factory = (SessionFactory) findBean(
              "FactoryName", context);
       SessionHolder holderInfo = (SessionHolder) TransactionSynchronizationManager
              .getResource(factory);
       if(holderInfo!=null){
           Session s = holderInfo.getSession();
           s.flush();//不想提交用s.clear()
           TransactionSynchronizationManager.unbindResource(factory);
           SessionFactoryUtils.releaseSession(s, factory);
       }
    }

备注:这里的ServletContext是接口,它对web容器来说定义了servlet环境对象(看字面意思是servelet上下文).对Jsf来说拿到它的方法为

ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

在读到Hibernate文档时说过SessionFactory创建代价很高,session相对较小,不过这个findBean是返回已有对象,而且由于Spring对项目来说,他的创建都追寻单例模式,对于sessionfactory应该不耗资源