我有一个提供配置数据的 Spring 服务。当 GUI 调用该服务时,它会从数据库中加载配置数据。事实证明,在呈现单个请求期间,这种情况经常发生。我想通过缓存配置数据来优化它。但是,我不确定这是否是一种好的编程风格,或者是否“允许”在服务中拥有实例变量。
下面是我想做的一些示例代码:
@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
}
}
最佳答案
有一个实例变量(不由 spring 管理)引入了服务变得线程不安全的可能性。所以我尽量避免使用它们,或者确保它们是线程安全的。
您可能需要查看 @configurable
和 @postconstuct
注释来实现您的目标。
关于java - Spring Services中是否允许有实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15024613/