我有一個提供配置數據的彈簧服務。當服務被GUI調用時,它從數據庫加載配置數據。事實證明,在呈現單個請求期間,這經常發生。我想通過緩存配置數據來優化它。但是,我不確定這是一種很好的編程風格,還是「允許」在服務中有實例變量。它允許在Spring服務中有實例變量嗎?
下面是我在想什麼做的一些示例代碼:
@Serivce("MyConfigService")
public class MyConfigServiceImpl implements MyConfigService {
private Config cachedConfig;
@Override
public Config loadConfig() {
if (cachedConfig != null) {
// load config
cachedConfig = loadedConfig;
}
return cachedConfig;
}
@Override
public saveConfig(Config config) {
cachedConfig = null;
// save the configuration
}
}
當然你可以這樣做,但我會建議讓你的服務初始化bean。通過這種方式,Spring在初始化bean時會自動調用特殊的回調函數,並且可以確保在任何其他服務可以開始使用bean之前完成初始化:http://www.mkyong.com/spring/spring-initializingbean-and-disposablebean-示例/ – 2013-02-22 13:00:28