@Lazy注解简单理解
解释:
因为spring默认是饿汉模式单例 初始化时就会加载bean,@Lazy注解的含义是延迟加载bean,只有在调用这个bean是才会加载
例子:
class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
System.out.println(" 对象被创建了.............");
this.name = name;
this.age = age;
}
}
public class funLazy {
@Lazy// 加不加有区别
@Bean
public Person person() {
return new Person("李四", 55);
}
}
public class ZJtest {
@Test
void test() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(funLazy.class);
ctx.getBean("person");// 加不加有区别
}
}
当不加@Lazy与ctx.getBean("person");时的结果
对象被创建了.............
当加@Lazy与不加ctx.getBean("person");时的结果
Process finished with exit code 0可以发现对象没有被创建
当加@Lazy与加ctx.getBean("person");时的结果
对象被创建了.............可以发现在加了@Lazy后再加ctx.getBean("person");即调用这个bean时才被会初始化 创建对象