正常状况下,bean的加载是容器启动后就开始的,这样若是加载的过程当中有错误,能够立马发现。因为一些特定的业务需求,须要某些bean在IoC容器在第一次请求时才建立,能够把这些bean标记为延时加载。spring
在XML配置文件中,是经过bean
标签的lazy-init
属性来控制的,若是控制多个bean都是懒加载,那么能够把bean放入beans
标签下面,经过beans
标签的default-lazy-init="true"
来控制。
xml配置:app
<?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"); } }
测试代码:spa
@Test public void test() { ApplicationContext app = new ClassPathXmlApplicationContext("di7.xml"); System.out.println("加载完毕"); app.getBean("one"); }
运行结果以下:
加载完毕以前,只打印了two init,调用getBean("one")后,才打印出one init,能够看出,是在调用后才加载。code
在注解中,是经过@Lazy来控制的。
MyConfigxml
@Configuration public class MyConfig { @Bean() @Lazy public One one(){ return new One(); } @Bean() public Two two(){ return new Two(); } }
测试代码blog
@Test public void test() { ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class); System.out.println("加载完毕"); app.getBean("one"); }
运行结果以下:get