@Lazy针对单实例的Bean有效。在Spring的容器初始化的时候不会实例化Bean,只有在第一次获取Bean的时候才会实例化Bean
配置信息
//告诉Spring这是一个配置文件
@Configuration
public class SpringConfig3 {
@Lazy
@Bean(name = "person")//给容器中注册一个bean
public Person getPerson() {
System.out.println("----->" + "getPerson");
return new Person("Lisi", 20);
}
}
实例化容器,但是没有获取Bean的时候,我们看不到:----->getPerson 信息的打印
@Test
public void testAnnotation3() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig3.class);
}
当我们连续从IOC容器中获取两次Bean的实例的时候,也会只有一次 ----->getPerson 信息的打印
@Test
public void testAnnotation3() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig3.class);
Person person1 = context.getBean(Person.class);
Person person2 = context.getBean(Person.class);
System.out.println(person1 == person2);
}