18

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

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.