懒加载@Lazy

Spring IOC容器规定在启动的时候回实例化所有的单实例Bean,如果想要Spring启动的时候延迟加载就可以使用@Lazy,在调用的时候再进行实例化

这篇文章短暂而又清晰

https://blog.csdn.net/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 才被初始化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值