默认情况下,Spring IoC 容器启动后,在初始化过程中,会以单例模式创建并配置所有使用 singleton 定义的 Bean 的实例。通常情况下,提前实例化 Bean是可取的,因为这样在配置中的任何错误就会很快被发现,否则可能要几个小时甚至几天后才会被发现。有时候你可能并不想在applicationContext初始化时提前实例化某个singleton定义的Bean,那么你可以将改Bean设置为延迟实例化。一个延迟实例化的Bean在第一次被请求的时候,Spring容器才会创建该Bean的实例,而不是在容器启动的时候。
在 Spring 配置文件中,将 <bean/> 元素的设置lazy-init 属性的值为 true,便可将该Bean 定义为延迟实例化的。默认情况下,所有的singleton Bean 都不是延迟实例化的。如果想让默认的情况下,所有的singleton Bean 都是延迟实例化的,可以将Spring 配置文件的根元素 <beans/> 的default-lazy-init 属性值设置为 true。
延迟实例化的示例Bean 的定义:
package com.huey.dream.bean;public class ExampleBean { public ExampleBean(String type) { System.out.println("In ExampleBean Constructor, Bean type is " + type); }}
Bean 的配置:
<bean id="eb1" class="com.huey.dream.bean.ExampleBean" lazy-init="true" > <constructor-arg name="type" value="lazyInitBean"/></bean><bean id="eb2" class="com.huey.dream.bean.ExampleBean"> <constructor-arg name="type" value="eagerInitBean"/></bean>
测试方法:
@Testpublic void testLazyInit() throws Exception { System.out.println("ApplicationContext 初始化开始!"); ApplicationContext appCtx = new ClassPathxmlApplicationContext("applicationContext.xml"); System.out.println("ApplicationContext 初始化完毕!"); ExampleBean eb1 = appCtx.getBean("eb1", ExampleBean.class); ExampleBean eb2 = appCtx.getBean("eb2", ExampleBean.class);}
结果输出:
ApplicationContext 初始化开始!2015-5-16 16:02:58 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1fddc31: startup date [Sat May 16 16:02:58 CST 2015]; root of context hierarchy2015-5-16 16:02:58 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [applicationContext.xml]2015-5-16 16:02:59 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@b1cc87: defining beans [eb1,eb2]; root of factory hierarchyIn ExampleBean Constructor, Bean type is eagerInitBeanApplicationContext 初始化完毕!In ExampleBean Constructor, Bean type is lazyInitBean
新闻热点
疑难解答