Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using `@Lazy` on a component constructor equal to annotating every argument?

In Spring, consider a @Service class, that has the following autowired constructor:

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

is this equivalent to?

@Lazy
public DogService(CatService catService, MouseService mouseService) {
  this.catService = catService;
  this.mouseService = mouseService;
}
like image 351
Michiel Haisma Avatar asked Mar 22 '18 16:03

Michiel Haisma


1 Answers

Yes, this is equivalent.

The @Lazy javadoc states :

In addition to its role for component initialization, this annotation may also be placed on injection points marked with org.springframework.beans.factory.annotation.Autowired or javax.inject.Inject: In that context, it leads to the creation of a lazy-resolution proxy for all affected dependencies, as an alternative to using org.springframework.beans.factory.ObjectFactory or javax.inject.Provider.

The important part is :

it leads to the creation of a lazy-resolution proxy for all affected dependencies

in terms of dependencies your DogService bean has two of them autowired in any case : CatService catService and MouseService mouseService.
So annotating the constructor or all parameters individually will produce the same result : the two dependencies will be lazy loaded.

Note : I have tested them and the behavior is exactly the same in both cases.

like image 59
davidxxx Avatar answered Oct 16 '22 19:10

davidxxx