【问题标题】:Make a request scoped bean singleton when request-scope is not available当请求范围不可用时,创建一个请求范围的 bean 单例
【发布时间】:2016-03-12 06:03:39
【问题描述】:

我有以下代码在我的 Spring 应用程序中定义一个 bean 请求范围的 bean。

@Bean       
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyBean myBean() {
    return new MyBean(); // actually it is a more complex initialization
}

但有时我会想在request 范围不可用的离线应用程序中使用相同的bean,只有singletonprototype 可用。

request 不可用时,有没有办法让同一个bean 呈现singleton 形式?

【问题讨论】:

    标签: java spring scope


    【解决方案1】:

    您可以依靠弹簧配置文件吗? 您可以使用 2 @Bean 使用不同的 @Scope@Profile 的私​​有方法提取 bean 创建

    类似这样的:

    @Bean     
    @Profile('prod')    
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public MyBean myBeanProd() {
        return getMyBean()
    }
    
    @Bean   
    @Profile('test')    
    @Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public MyBean myBeanWithoutRequestScope() {
        return getMyBean()
    }
    
    privateMyBean getMyBean() {
        return new MyBean(); // actually it is a more complex initialization
    }
    

    【讨论】:

    • 效果很好。我以前从未使用过@Profile
    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 2019-12-01
    • 2017-01-22
    • 2013-01-21
    • 1970-01-01
    • 2011-11-11
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多