总结
单实例bean:默认在容器启动的时候创建对象;
懒加载:容器启动不创建对象。第一次使用(获取)Bean创建对象,并初始化
;
不加@Lazy测试发现:
1.单例bean默认在容器启动的时候创建并初始化添加到IOC容器,然后每次调用都从容器中取
2.打印了System.out.println(“给容器中添加Person…”);
@Bean("person")
public Person person(){
System.out.println("给容器中添加Person....");
return new Person("张三", 25);
}
@Test
public void test2020(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2020.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
System.out.println("ioc容器创建完成....");
}
十一月 14, 2020 10:47:32 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a996b: startup date [Sat Nov 14 22:47:32 CST 2020]; root of context hierarchy
十一月 14, 2020 10:47:32 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
给容器中添加Person....
ioc容器创建完成....
true
添加@Lazy 后测试发现
1.单例bean默认并没有随IOC容器启动而创建实例对象,
2.而是当调用时才创建的单例对象并初始化添加到IOC容器的
@Lazy
@Bean("person")
public Person person(){
System.out.println("给容器中添加Person....");
return new Person("张三", 25);
}
@Test
public void test2020(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2020.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
System.out.println("ioc容器创建完成....");
Object bean = applicationContext.getBean("person");
Object bean2 = applicationContext.getBean("person");
System.out.println(bean == bean2);
}
十一月 14, 2020 10:42:18 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a996b: startup date [Sat Nov 14 22:42:18 CST 2020]; root of context hierarchy
十一月 14, 2020 10:42:18 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
ioc容器创建完成....
给容器中添加Person....
true