lazy 懒加载,主要针对单实例bean,容器启动时候不创建对象,仅当第一次使用的bean才创建
新建Cap4MainConfig.java
package com.caojiulu.cap4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import com.caojiulu.cap1.bean.Person;
@Configuration
public class Cap4MainConfig {
//给容器中注册bean,类型为返回值的类型,默认是单实例
/**
* 懒加载:主要针对单实例bean,:默认是容器启动的时候创建对象
* 加上lazy,容器启动时候不创建对象,仅当第一次使用的bean才创建
* @return
*/
@Lazy
@Bean
public Person person(){
System.out.println("22222");
return new Person("caojiulu",24);
}
}
2,建立测试用例test01();
package com.caojiulu.cap4;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Cap4Test {
@Test
public void test01(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap4MainConfig.class);
String[] beanDefinitionNames = app.getBeanDefinitionNames();
for (String name : beanDefinitionNames) {
System.out.println("bean -->"+name);
}
Object bean1 = app.getBean("person");
Object bean2 = app.getBean("person");
System.out.println(bean1==bean2);
}
}
当在Cap4MainConfig加入@Lazy时, 只有获取anno.getBean时才会加载到IOC容器中