在组件构造函数上使用`@Lazy`等于注释每个参数?

Mic*_*sma 6 java spring dependency-injection spring-boot

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

public DogService(@Lazy CatService catService, @Lazy MouseService mouseService) {
  this.catService = catService;
  this.mouseService = mouseService;
}
Run Code Online (Sandbox Code Playgroud)

这相当于?

@Lazy
public DogService(CatService catService, MouseService mouseService) {
  this.catService = catService;
  this.mouseService = mouseService;
}
Run Code Online (Sandbox Code Playgroud)

dav*_*xxx 7

是的,这是等价的。

@Lazyjavadoc的状态:

除了它在组件初始化中的作用之外,这个注解也可以被放置在用org.springframework.beans.factory.annotation.Autowired或 标记的注入点上 javax.inject.Inject:在这种情况下,它会导致为所有受影响的依赖项创建一个延迟解析代理,作为using org.springframework.beans.factory.ObjectFactory或 的替代javax.inject.Provider

重要的部分是:

它导致为所有受影响的依赖项创建一个延迟解析代理

就依赖项而言,您的DogServicebean 在任何情况下都会自动装配其中两个 :CatService catServiceMouseService mouseService.
因此,单独注释构造函数或所有参数将产生相同的结果:两个依赖项将被延迟加载。

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