Spring IOC容器规定在启动的时候回实例化所有的单实例Bean,如果想要Spring启动的时候延迟加载就可以使用@Lazy,在调用的时候再进行实例化
这篇文章短暂而又清晰
https://blog.youkuaiyun.com/weixin_41888813/article/details/102947633
使用@Autowired
这里,为了初始化一个懒惰的bean,我们从另一个bean中引用它。
我们想要懒惰加载的bean:
@Lazy
@Component
public class City {
public City() {
System.out.println("City bean initialized");
}
}
public class Region {
@Lazy
@Autowired
private City city;
public Region() {
System.out.println("Region bean initialized");
}
public City getCityInstance() {
return city;
}
}
请注意,@ Lazy在两个地方都是强制性的。
使用City类上的@Component注解并在使用@Autowired引用它时:
@Test
public void givenLazyAnnotation_whenAutowire_thenLazyBean() {
// load up ctx appication context
Region region = ctx.getBean(Region.class);
region.getCityInstance();
}
在这里,当我们调用getCityInstance() 方法时,city bean 才被初始化。