默認情況下,Spring IoC 容器啟動后,在初始化過程中,會以單例模式創(chuàng)建并配置所有使用 singleton 定義的 Bean 的實例。通常情況下,提前實例化 Bean是可取的,因為這樣在配置中的任何錯誤就會很快被發(fā)現(xiàn),否則可能要幾個小時甚至幾天后才會被發(fā)現(xiàn)。有時候你可能并不想在applicationContext初始化時提前實例化某個singleton定義的Bean,那么你可以將改Bean設(shè)置為延遲實例化。一個延遲實例化的Bean在第一次被請求的時候,Spring容器才會創(chuàng)建該Bean的實例,而不是在容器啟動的時候。
在 Spring 配置文件中,將 <bean/> 元素的設(shè)置lazy-init 屬性的值為 true,便可將該Bean 定義為延遲實例化的。默認情況下,所有的singleton Bean 都不是延遲實例化的。如果想讓默認的情況下,所有的singleton Bean 都是延遲實例化的,可以將Spring 配置文件的根元素 <beans/> 的default-lazy-init 屬性值設(shè)置為 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);}結(jié)果輸出:
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
新聞熱點
疑難解答