javaspring-bootspring-beanrequestscope

Does Spring's @RequestScope automatically handle proxying when injected in singleton beans?


I'm using a Java8/Spring Boot 2 application. I want to inject a request-scoped bean into a singleton bean. The official documentation highlights that either a proxy or ObjectFactory/Provider should be used to ensure always getting the correctly scoped bean at runtime in the singleton bean. However, the @RequestScope annotation seems to "automatically" set some kind of proxy, as explained in the answer to this question.

I'm now wondering if the following three implementations are in fact identical and which one is preferred?

Approach 1: explicitly using objectFactory<>

@Component
@RequestScope
public class MyRequestScopedBean{...}

@Component
public class MySingletonBean{
    @Autowired
    private ObjectFactory<MyRequestScopedBean> myRequestScopedBean
}

Approach 2: inject normally, assuming the request scoped bean is proxied automatically?

@Component
@RequestScope
public class MyRequestScopedBean{...}

@Component
public class MySingletonBean{
    @Autowired
    private MyRequestScopedBean myRequestScopedBean
}

Approach 3: using @Configuration and @Bean because I don't know the difference and I'm worried they behave differently.

@Comfiguration
public class myBeanConfig{
   @Bean
   @RequestScope
   public MyRequestScopedBean getRequestScopedBean(){return new MyRequestScopedBean();}

}

@Component
public class MySingletonBean{
    @Autowired
    private MyRequestScopedBean myRequestScopedBean
}

I would prefer approach 2, because it is concise and handles the scoping/proxying automatically.

Would the answer change if my @Autowired bean is declared as a final field? I'm worried making it final somehow prevents the proxy from fetching the correctly fetching the new bean every request.


Solution

  • I have been using the 2nd approach in my projects and I have zero issues so far. The documentation does not mention it's a MUST to use ObjectFactory too. Don't think too much. If you run into any problems, you will see the error very clearly in the console. There's no reason to be afraid until you have an actual issue to deal with.