spring bean 懒加载中bean默认是延迟加载吗

spring&3.x&+&hibernate4.x&实现数据延迟加载
Spring为我们解决Hibernate的Session的关闭与开启问题。&
Hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session
范围之内进行。如果 Service 层返回一个启用了延迟加载功能的领域对象给 Web 层,当 Web
层访问到那些需要延迟加载的数据时,由于加载领域对象的 Hibernate Session
已经关闭,这些导致延迟加载数据的访问异常
org.hibernate.LazyInitializationException:(LazyInitializationException.java:42)&
- failed to lazily initialize a collection of role:
cn.easyjava.bean.product.ProductType.childtypes, no session or
session was closed&
org.hibernate.LazyInitializationException: failed to lazily
initialize a collection of role:
cn.easyjava.bean.product.ProductType.childtypes, no session or
session was closed)
&解决方方法可以用过滤器也可以用拦截器
方法1: 利用org.springframework.orm.hibernate4.support.OpenSessionInViewFilter,在web.xml中配置
OperSessionInViewFilter.
&filter-name&openSessionInViewFilter&/filter-name&
&filter-class&org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
&/filter-class&
&init-param&
&param-name&sessionFactoryBeanName&/param-name&
&param-value&sessionFactory&/param-value&
&/init-param&
&/filter&&
&filter-mapping&
&filter-name&openSessionInViewFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
注意:sessionFactiory
是自己在springContext中定义的&org.springframework.orm.hibernate4.LocalSessionFactoryBean的实例(一般在appricationContext.xml中定义)
方法二:利用org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor,在appricationContext.xml
&bean name="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor"&
name="sessionFactory"&
&ref bean="sessionFactory"
&/property&
&bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&
name="interceptors"&
&ref bean="openSessionInViewInterceptor"
&/property&
&property name="mappings"&
&value&/*&/value&
&!-- 需要拦截的url --&
&/property&
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
注 : 一般是 ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
配置初始化
1. 在struts-config.xml里,以插件的形式
&&plug-in&className="org.springframework.web.struts.ContextLoaderPlugIn"&/&&&&
&&&&&&set-property&property="contextConfigLocation"&value="/WEB-INF/applicationContext.xml"&/&&&&
&&/&plug-in&&&&&
这种方式如果没有配置contextConfigLocation的值,则会自动加载xx-servlet.xml.
xx的值是和web.xml里的配置org.apache.struts.action.ActionServlet的servlet-name的值一样
如下:xx的值也就是&action,所以会自动加载action-servlet.xml
&&servlet&&&&
&&&&&&servlet-name&&action&&/&servlet-name&&&&
&&&&&&servlet-class&&org.apache.struts.action.ActionServlet&&/&servlet-class&&&&
&&&&&&load-on-startup&&1&&/&load-on-startup&&&&
&&&&/&servlet&&&&
&&&&servlet-mapping&&&&
&&&&&&servlet-name&&action&&/&servlet-name&&&&
&&&&&&url-pattern&&*.do&&/&url-pattern&&&&
&&&&/&servlet-mapping&&&&
&如果sturts-config.xml里配置了contextConfigLocation的值,那么就不会自动加载xx-servlet.xml了,而只会加载contextConfigLocation所指定的xml.
&2. 第2种方式
在web.xml里配置Listener
&listener&&&
&&&&&&&&&&&listener-class&org.springframework.web.context.ContextLoaderListenerlistener-class&&&
&&&&&&&/&&listener&&&
如果在web.xml里给该Listener指定要加载的xml,如:
&context-param&&&
&&&&&&&&&param-name&contextConfigLocation&/param-name&&&
&&&&&&&&&param-value&classpath*:spring/*.xml&/param-value&&&
&&&&/&context-param&&&
则会去加载相应的xml,而不会去加载/WEB-INF/下的applicationContext.xml。。但是,如果没有指定的话,默认会去/WEB-INF/下加载applicationContext.xml。
3. 第三种方式:ContextLoaderServlet
&&servlet&& &&
&&&&&&&&&&servlet-name&context&&/&servlet-name&& &&
&&&&&&&&&&servlet-class&org.springframework.web.context.ContextLoaderServlet&&/&servlet-class&& &&
&&&&&&&&&&load-on-startup&1&&/&load-on-startup&& &&
&&&&&&/&servlet&&&
&这种方式和第二种Listener方式一样,唯一的区别就是用Listener方式初始化ApplicationContext,可以和用第一种方式(struts-config.xml里 plugin方式)同时存在,而ContextLoaderServlet则不可以和第一种方式同时存在
如一个完整的web.xml配置文件
&?xml version="1.0" encoding="UTF-8"?&&web-app version="2.5" &xmlns="" &xmlns:xsi="" &xsi:schemaLocation="&"&&&context-param&&&&&&&& &param-name&contextConfigLocation&/param-name&&&&&&&& &param-value&/WEB-INF/applicationContext-*.xml&/param-value&&&& &/context-param&&&& &servlet&&&&&&&& &servlet-name&controller&/servlet-name&&&&&&&& &servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&&&&&&&& &load-on-startup&1&/load-on-startup&&&& &/servlet&&&&& &!--& &&&& &servlet&&&&&&&& &servlet-name&context&/servlet-name&&&&&&&& &servlet-class&org.springframework.web.context.ContextLoaderServlet&/servlet-class&&&&&&&& &load-on-startup&1&/load-on-startup&&&& &/servlet&&&& --&&&& &listener& &&&& &listener-class& &&&&&&&&& org.springframework.web.context.ContextLoaderListener &&&& &/listener-class& && &/listener&&&& &servlet-mapping&&&&&&&& &servlet-name&controller&/servlet-name&&&&&&&& &url-pattern&*.htm&/url-pattern&&&& &/servlet-mapping&& &&welcome-file-list&&&& &&welcome-file&index.jsp&/welcome-file&& &&/welcome-file-list&&/web-app&
ContextLoaderServlet已经不推荐用了,它只是为了兼容低版本的servlet.jar才用的。
总的来说:Listerner要比Servlet更好一些,而且Listerner监听应用的启动和结束,而Servlet启动要稍微延迟一些。
阅读(2111)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'Spring中ApplicationContext加载机制和配置初始化',
blogAbstract:'Spring中ApplicationContext加载机制。 &&&&&& 加载器目前有两种选择:ContextLoaderListener和ContextLoaderServlet。 &&&&&& 这两者在功能上完全等同,只是一个是基于Servlet2.3版本中新引入的Listener接口实现,而另一个基于Servlet接口实现。开发中可根据目标Web容器的实际情况进行选择。
配置非常简单,在web.xml中增加:&
ContextLoaderServlet:',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:0,
publishTime:0,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:true,
hostIntro:'',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}本帖子已过去太久远了,不再提供回复功能。Spring中初始化bean和销毁bean的时候执行某个方法的详解 - 博客频道 - CSDN.NET
NextX工作室的博客
NextX工作室强大开发团队~Come on~~~
分类:Spring
import&javax.annotation.PostC&&&&import&javax.annotation.PreD&&&&&&public&class&DataInitializer{&&&&&&&&&@PostConstruct&&&&&&public&void&initMethod()&throws&Exception&{&&&&&&&&&&System.out.println(&initMethod&被执行&);&&&&&&}&&&&&&@PreDestroy&&&&&&public&void&destroyMethod()&throws&Exception&{&&&&&&&&&&System.out.println(&destroyMethod&被执行&);&&&&&&}&&}&&
第二种是:
public&class&DataInitializer{&&&&&&public&void&initMethod()&throws&Exception&{&&&&&&&&&&System.out.println(&initMethod&被执行&);&&&&&&}&&&&&&public&void&destroyMethod()&throws&Exception&{&&&&&&&&&&System.out.println(&destroyMethod&被执行&);&&&&&&}&&}&&
&id=&dataInitializer&&class=&com.somnus.demo.DataInitializer&&init-method=&initMethod&&destory-method=&destroyMethod&&&
第三种是:
import&org.springframework.beans.factory.DisposableB&&&&public&class&DataInitializer&implements&InitializingBean,DisposableBean{&&&&&&&&&&&&@Override&&&&&&public&void&afterPropertiesSet()&throws&Exception&{&&&&&&&&&&System.out.println(&afterPropertiesSet&被执行&);&&&&&&}&&&&&&&&&&&&@Override&&&&&&public&void&destroy()&throws&Exception&{&&&&&&&&&&System.out.println(&destroy&被执行&);&&&&&&}&&&&}&&
其中第一种和第二种是同一种形式,只不过一种xml配置,另外一种采用注解形式罢了,有很大区别的是第三种,
如果同一个bean同时采用两种方式初始化的时候执行某个方法,首先在执行顺序上就会体现出来。
先执行afterPropertiesSet(),
后执行initMethod()
这里我们看下源码
这方式在spring中是怎么实现的?
通过查看spring的加载bean的源码类(AbstractAutowireCapableBeanFactory)可看出其中奥妙
AbstractAutowireCapableBeanFactory类中的invokeInitMethods讲解的非常清楚,源码如下:
protected&void&invokeInitMethods(String&beanName,&final&Object&bean,&RootBeanDefinition&mbd)&&&&&&&&throws&Throwable&{&&&&&&&&boolean&isInitializingBean&=&(bean&instanceof&InitializingBean);&&&&if&(isInitializingBean&&&&(mbd&==&null&||&!mbd.isExternallyManagedInitMethod(&afterPropertiesSet&)))&{&&&&&&&&if&(logger.isDebugEnabled())&{&&&&&&&&&&&&logger.debug(&Invoking&afterPropertiesSet()&on&bean&with&name&'&&+&beanName&+&&'&);&&&&&&&&}&&&&&&&&&&&&&&&&if&(System.getSecurityManager()&!=&null)&{&&&&&&&&&&&&try&{&&&&&&&&&&&&&&&&AccessController.doPrivileged(new&PrivilegedExceptionAction&Object&()&{&&&&&&&&&&&&&&&&&&&&public&Object&run()&throws&Exception&{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&((InitializingBean)&bean).afterPropertiesSet();&&&&&&&&&&&&&&&&&&&&&&&&return&null;&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&},getAccessControlContext());&&&&&&&&&&&&}&catch&(PrivilegedActionException&pae)&{&&&&&&&&&&&&&&&&throw&pae.getException();&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&else&{&&&&&&&&&&&&&&&&&&&&&&&&((InitializingBean)&bean).afterPropertiesSet();&&&&&&&&}&&&&}&&&&if&(mbd&!=&null)&{&&&&&&&&String&initMethodName&=&mbd.getInitMethodName();&&&&&&&&&&&&&&&&if&(initMethodName&!=&null&&&&!(isInitializingBean&&&&&afterPropertiesSet&.equals(initMethodName))&&&&&&&&&&&&&&&&&&&!mbd.isExternallyManagedInitMethod(initMethodName))&{&&&&&&&&&&&&&&&&&&&&&&&&&&&&invokeCustomInitMethod(beanName,&bean,&mbd);&&&&&&&&}&&&&}&&
1:spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过
init-method指定,两种方式可以同时使用
2:实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是
init-method方式消除了对spring的依赖
3:如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。
排名:千里之外
(3)(16)(2)(7)(2)(1)(6)(1)(1)(2)(4)(2)(1)(2)(1)(2)(2)(1)

我要回帖

更多关于 spring bean 懒加载 的文章

 

随机推荐