Issue
A component is defined with request scope, it provides data based on HttpServletRequest
object as shown below.
@Component
@RequestScope
@Getter
public class RequestDataHolder {
private final Object data;
public RequestDataHolder(HttpServletRequest request) {
data = //costly operations;
}
}
When is the component instantiated? I would like to prevent the costly operations when data is not needed, so was thinking about annotating the component with @Lazy
, but if it is instantiated when accessed by default, the annotation would be redundant.
Solution
According to docs.spring.io:
@RequestScope is a composed annotation that acts as a shortcut for @Scope("request") with the default proxyMode() set to TARGET_CLASS.
This means that the request scoped bean is provided as a CGLIB proxy by default when injected into a singleton bean. The proxy either instantiate the bean or reuse the existing one.
The bean is instantiated when its proxy's method is invoked, which produces the same effect as the @Lazy
annotation.
Answered By - birca123
Answer Checked By - David Goodson (JavaFixing Volunteer)