java - Spring Services中是否允许有实例变量?

标签 java spring service

我有一个提供配置数据的 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/

相关文章:

java - MAC-STS 4 "Failed to create the Java Virtual Machine"

java - IntellijIdea 无法自动重新加载 Web 应用程序(热部署)JSP 和 Javascript Debug模式下的更改

java - 使用 ProGuard 导出 Android 应用程序会出现 ParseException 错误

android - 方法编译错误以检查服务是否正在运行

linux - 重启 daemontools 服务的更好方法是什么?

java - 无法使用 HttpClient 读取浏览器 cookie

java - 如何为 @ResponseStatus 创建分支结果

java - 使用 Spring 根据用户输入在运行时 Autowiring 属性

java - 无注释的程序化 Bean 验证 (JSR 303)

c# windows 服务配置文件