当注入单例 bean 时,Spring 的 @RequestScope 是否会自动处理代理? [英] Does Spring's @RequestScope automatically handle proxying when injected in singleton beans?

查看:39
本文介绍了当注入单例 bean 时,Spring 的 @RequestScope 是否会自动处理代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Java8/Spring Boot 2 应用程序.我想将请求范围的 bean 注入到单例 bean 中.官方文档 强调应该使用代理或 ObjectFactory/Provider 来确保在运行时始终在单例 bean 中获得正确作用域的 bean.但是,@RequestScope 注释似乎自动"设置了某种代理,如对 这个问题.

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?

方法一:显式使用objectFactory<>

Approach 1: explicitly using objectFactory<>

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

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

方法二:正常注入,假设请求范围的bean是自动代理的?

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
}

方法 3:使用 @Configuration 和 @Bean,因为我不知道它们的区别,而且我担心它们的行为不同.

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
}

我更喜欢方法 2,因为它简洁且自动处理范围/代理.

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

如果我的@Autowired bean 被声明为 final 字段,答案会改变吗?我担心使其最终以某种方式阻止代理获取正确获取每个请求的新 bean.

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.

推荐答案

我一直在我的项目中使用第二种方法,到目前为止我的问题为零.文档没有提到它也必须使用 ObjectFactory.不要想太多.如果您遇到任何问题,您将在控制台中非常清楚地看到错误.除非您有实际问题需要处理,否则没有理由害怕.

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.

这篇关于当注入单例 bean 时,Spring 的 @RequestScope 是否会自动处理代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆