【问题标题】:Is using `@Lazy` on a component constructor equal to annotating every argument?在组件构造函数上使用 `@Lazy` 是否等于注释每个参数?
【发布时间】:2018-09-01 04:51:16
【问题描述】:

在 Spring 中,考虑一个 @Service 类,它具有以下自动装配的构造函数:

public DogService(@Lazy CatService catService, @Lazy MouseService mouseService) {
  this.catService = catService;
  this.mouseService = mouseService;
}

这相当于吗?

@Lazy
public DogService(CatService catService, MouseService mouseService) {
  this.catService = catService;
  this.mouseService = mouseService;
}

【问题讨论】:

    标签: java spring spring-boot dependency-injection


    【解决方案1】:

    是的,这是等价的。

    @Lazy javadoc 声明:

    这个注解除了对组件初始化的作用外, 也可以放置在标有 org.springframework.beans.factory.annotation.Autowiredjavax.inject.Inject:在这种情况下,它会导致创建一个 所有受影响依赖项的惰性解析代理,作为替代 到using org.springframework.beans.factory.ObjectFactoryjavax.inject.Provider.

    重要的部分是:

    它会为所有受影响的人创建一个惰性解析代理 依赖关系

    就依赖关系而言,您的 DogService bean 无论如何都会自动装配其中两个:CatService catServiceMouseService mouseService
    所以单独注释构造函数或所有参数将产生相同的结果:两个依赖项将被延迟加载。

    注意:我已经对它们进行了测试,两种情况下的行为完全相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      相关资源
      最近更新 更多