Lazy

正常情况下,bean的加载是容器启动后就开始的,这样如果加载的过程中有错误,可以立马发现。由于一些特定的业务需求,需要某些bean在IoC容器在第一次请求时才创建,可以把这些bean标记为延时加载。

XML

在XML配置文件中,是通过bean标签的lazy-init属性来控制的,如果控制多个bean都是懒加载,那么可以把bean放入beans标签下面,通过beans标签的default-lazy-init="true"来控制。
xml配置:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"       xmlns:p="http://www.springframework.org/schema/p"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="one" class="com.learn.di.One" lazy-init="true"/>    <bean id="two" class="com.learn.di.Two"/></beans>

One和Two

public class One {    public One(){        System.out.println("one init");    }}public class Two {    public Two(){        System.out.println("two init");    }}

测试代码:

@Testpublic void test() {    ApplicationContext app = new ClassPathXmlApplicationContext("di7.xml");    System.out.println("加载完毕");    app.getBean("one");}

运行结果如下:

加载完毕之前,只打印了two init,调用getBean("one")后,才打印出one init,可以看出,是在调用后才加载。

注解

在注解中,是通过@Lazy来控制的。
MyConfig

@Configurationpublic class MyConfig {    @Bean()    @Lazy    public One one(){        return new One();    }    @Bean()    public Two two(){        return new Two();    }}

测试代码

@Testpublic void test() {    ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);    System.out.println("加载完毕");    app.getBean("one");}

运行结果如下: