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

五迷三道 提交于 2019-12-07 15:37:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/56217321/does-springs-requestscope-automatically-handle-proxying-when-injected-in-singl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!