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.