简体   繁体   中英

Is component defined with request scope lazy loaded?

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.

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.

When we configure a bean with lazy initialization, the bean will only be created, and its dependencies injected, once they're needed. So when you will be accessing the costly data, then only this method will be invoked. So then the use of @Lazy will not be redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM