Spring(3.2.3) - Beans(7): 延迟实例化

默认情况下,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>

测试方法:

@Test
public 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 hierarchy
2015-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 hierarchy
In ExampleBean Constructor, Bean type is eagerInitBean
ApplicationContext 初始化完毕!
In ExampleBean Constructor, Bean type is lazyInitBean

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。