2016-03-12 33 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'。 –