Spring的findBean和sessionBind

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

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


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

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));
}
}


[color=red]//请求之后要解绑!![/color]

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应该不耗资源
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值