2016-03-12 32 views
1

我有以下代码来在我的Spring应用程序中定义一个bean请求作用域bean。当请求范围不可用时,请求作用域bean singleton

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

但有时我会想在脱机应用程序使用同一个bean那里request范围不可,只有singletonprototype是。

request不可用时,是否有办法使这个相同的bean假定为singleton表单?

回答

1

你能依靠春天的个人资料吗? 也许你可以提取bean创建与不同@Scope@Profile

东西使用2 @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 
} 
+0

它非常好。我以前使用'@ Profile'。 –