Michiel Haisma
Michiel Haisma

Reputation: 874

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;
}

Upvotes: 18

Views: 13316

Answers (1)

davidxxx
davidxxx

Reputation: 131376

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.

Upvotes: 20

Related Questions