Spring IoC (ApplicationContext) 容器一般都会在启动的时候实例化所有单实例 bean 。如果我们想要 Spring 在启动的时候延迟加载 bean,即在调用某个 bean 的时候再去初始化,那么就可以使用 @Lazy 注解。
@Lazy 的属性
value 取值有 true 和 false 两个 默认值为 true
true 表示使用 延迟加载, false 表示不使用,false 纯属多余,如果不使用,不标注该注解就可以了。
Person 类
public 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;}// 省略 getter setter 和 toString 方法}
配置类 不标注 @Lazy 注解
public class LazyConfig {@Beanpublic Person person() {return new Person("李四", 55);}}
测试
@Testpublic void test5() {ApplicationContext ctx = new AnnotationConfigApplicationContext(LazyConfig.class);}
不获取 bean , 看控制台是否会打印。如果有打印,代表调用了构造器。
结果

在配置类打上 @Lazy 注解
public class LazyConfig {@Lazy@Beanpublic Person person() {return new Person("李四", 55);}}
再来看输出结果
T
没有打印语句,对象没有调用构造器,那么方法也就没有被创建。
@Lazy(value = false) 或者 @Lazy(false) 那么对象会在初始化的时候被创建
@Lazy注解注解的作用主要是减少springIOC容器启动的加载时间
当出现循环依赖时,也可以添加@Lazy
spring使用@Autowired为抽象父类注入依赖
有时候为了管理或者避免不一致性,希望具体服务统一继承抽象父类,同时不同子类具体服务使用@Autowired为抽象父类注入不同的子类依赖。
经仔细研究与测试,只要父类要注入的属性是protected保护级别即可,如下:
父类:
public class Father {@Lazy@Autowiredprotected Person p;}
子类:
@Configurationpublic class Son extends Father{@Bean("p1")public Person getPerson(){return new Person(1);}}
@Configurationpublic class Son2 extends Father{@Bean("p2")public Person getPerson(){return new Person(2);}}
注意,@Bean默认使用方法名作为bean名称,这里要指定名称,防止冲突。
测试:
@SpringBootTest(classes = DemoApplication.class)@RunWith(SpringRunner.class)@FixMethodOrder(MethodSorters.NAME_ASCENDING)public class FatherTest {@Autowiredprivate Son s1;@Autowiredprivate Son2 s2;@Testpublic void test(){System.out.println(s1.getPerson().getAge());System.out.println(s2.getPerson().getAge());}}
结果:
2021-08-12 15:58:08.769 INFO 12160 --- [ main] com.example.lazy.FatherTest : Started FatherTest in 4.715 seconds (JVM running for 5.61)12
