Spring的@RequestScope注入单例bean时是否自动处理代理?

时间:2019-05-20 08:48:28

标签: java spring-boot spring-bean requestscope

我正在使用Java8 / Spring Boot 2应用程序。我想将请求范围的bean注入到singleton bean中。 official documentation强调指出,应该使用代理或ObjectFactory / Provider来确保始终在运行时在单例bean中获得正确范围的bean。但是,@ RequestScope批注似乎是“自动”设置某种代理,如对this question的回答所述。

我现在想知道以下三种实现方式是否完全相同,哪种更可取?

方法1:显式使用objectFactory <>

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

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

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

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

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

方法3:使用@Configuration和@Bean,因为我不知道它们之间的区别,我担心它们的行为会有所不同。

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

}

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

我更喜欢方法2,因为它简洁明了,并且可以自动处理作用域/代理。

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

1 个答案:

答案 0 :(得分:1)

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