Spring (3.2.3), spring3.2.3
By default, after the Spring IoC container is started, all instances of beans defined by singleton are created and configured in singleton mode during initialization. Generally, it is advisable to instantiate the Bean in advance, because any errors in the configuration will soon be detected, otherwise it may take several hours or even days to be discovered. Sometimes you may not want to instantiate a singleton-defined Bean in advance during ApplicationContext initialization, so you can set the Bean to delayed instantiation. When a delayed Bean is requested for the first time, the Spring container will create the Bean instance instead of when the container starts.
In the Spring configuration file, set the value of the lazy-init attribute of the <bean/> element to true to define the Bean as delayed instantiation. By default, all singleton beans do not delay instantiation. If you want all singleton beans to be instantiated by default, you can set the default-lazy-init attribute value of the root element <beans/> of the Spring configuration file to true.
Example of delayed instantiation
Bean definition:
package com.huey.dream.bean;public class ExampleBean { public ExampleBean(String type) { System.out.println("In ExampleBean Constructor, Bean type is " + type); }}
Bean Configuration:
<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>
Test method:
@ Testpublic void testLazyInit () throws Exception {System. out. println ("ApplicationContext initialization starts! "); ApplicationContext appCtx = new ClassPathXmlApplicationContext (" applicationContext. xml "); System. out. println (" ApplicationContext Initialization is complete! "); ExampleBean eb1 = appCtx. getBean (" eb1 ", ExampleBean. class); ExampleBean eb2 = appCtx. getBean (" eb2 ", ExampleBean. class );}
Result output:
ApplicationContext initialization starts! 16:02:58 org. springframework. context. support. classPathXmlApplicationContext prepareRefresh information: 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 information: Loading XML bean definitions from cl Ass path resource [applicationContext. xml] 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 Initialization is complete! In ExampleBean Constructor, Bean type is lazyInitBean