I have an error about The dependencies of some of the beans in the application context form a cycle:
.
and many answers suggest using @Lazy
annotation to fix this problem
but what is the impact on the code after using @Lazy
??
The cycle happened because two services injected each other
and I read about @Lazy
,and how it fix this issue by @Lazy
That is:
instead of fully initializing the bean, it will create a proxy to inject it into the other bean. The injected bean will only be fully created when it’s first needed.
CodePudding user response:
No matter which injection method you use, in all cases instead of a reference to a real dependency, a proxy object is provided.
It’s important to understand that if a relation is marked with @Lazy it doesn’t mean that creation of the dependent bean is postponed. When the dependent bean isn’t marked with @Lazy itself, it will be eagerly created by the Spring container. Such behavior leads to the conclusion that lazy injection should be mainly used together with lazy initialization.
source: https://www.javacodegeeks.com/2018/03/spring-lazy-annotation-use-cases.html
CodePudding user response:
This is to add to Abdalrhman's answer...
The @Lazy
annotation is used to delay the initialization of a bean.
Delay until when? When it is needed. The inverse, if a bean is not annotated with @Lazy
, its proxy object initializes it when the proxy object is initialized (on application context initialization). If a bean is annotated with @Lazy
, its proxy object is still be initialized on application context initialization, but it underlying object is not initialized until an instance is requested. If it is a singleton bean, then the value is cached for later.
Why? It can be useful in situations where creating a bean is time-consuming or resource-intensive.
Note: You can make a single bean lazily-initialized by annotating the method. You can make all beans in a class (e.g., @Configuration
) lazily-initialized by annotating the class.
Resources:
- https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Lazy.html
- https://www.baeldung.com/spring-lazy-annotation
Fun fact: Some DI frameworks use lazy-initialization by default, specifically, Guice and HK2.