前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring之@Lazy懒加载

Spring之@Lazy懒加载

作者头像
叔牙
发布2020-11-19 17:43:07
1.7K0
发布2020-11-19 17:43:07
举报

Spring之@Lazy懒加载

在本文中,我们将介绍和讨论Spring @Lazy注解。

简介

默认情况下,Spring IoC在应用程序启动时创建并初始化所有单例bean。这种默认行为可确保立即捕获任何可能的错误。

此功能非常适合避免任何运行时错误,但是在一些场景中,我们希望Spring IoC在启动时不创建bean,但在应用程序请求时创建它。

Spring @Lazy注解可用于防止单例bean的预初始化。

1

Spring @Lazy 注解

@Lazy注解适用于版本为3.0以上的Spring框架。此注解用于直接或间接使用@Component注解的任何类或使用@Bean注解的方法。

1.1:@Configuration类级别注解

如果@Configuration类中存在@Lazy,则表明该@Configuration中的所有@Bean方法都应该被懒惰地初始化。

@Lazy @Configuration @ComponentScan(basePackages = "com.typhoon.rest") public class LazyAppConfig { @Bean public CustomerService customerService(){ return new CustomerService(); } @Bean public UserService userService(){ return new UserServiceImpl(); } }

在这种情况下,LazyAppConfig类下定义的所有bean仅在第一次请求时才初始化。便于测试,我们可以运行一个简单的单元测试用例。

@Test public void test_lazy_bean_init(){ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(LazyAppConfig.class); context.refresh(); context.getBean(CustomerService.class); context.getBean(UserService.class); }

1.2:Bean懒初始化

我们可以选择在bean级别定义/声明@Lazy注解。@Lazy存在且在用@Lazy注解的@Configuration类中的@Bean方法上为false,这表示覆盖'默认懒加载'行为和bean预初始化。

@Configuration @ComponentScan(basePackages = "com.typhoon.rest") public class LazyAppConfig { @Lazy(true) //true is the default value. @Bean public CustomerService customerService(){ return new CustomerService(); } @Lazy(false) @Bean public UserService userService(){ return new UserServiceImpl(); } }

1.3:@Autowired或@Inject级别注解

我们可以在@Autowired或@Inject注解上使用@Lazy注解。当放在这些注解上时,即依赖注入也是延迟的。

@Lazy @Component public class OrderService { //business logic } OrderFacade使用OrderService: public class OrderFacade { @Lazy @Autowired private OrderService orderService; public OrderDto getOrderById(String id){ return convertToOrderDto(orderService.getOrderById(id)); } }

这样,当我们使用orderService时才会注入依赖,即延迟依赖注入到使用时。

总结

在这篇文章中,我们介绍了Spring @Lazy注解的不同功能。我们了解了如何控制Spring单例bean的预初始化以及配置和使用@Lazy注解的不同方式。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-12-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 PersistentCoder 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档