【问题标题】:modifying property of a bean with singleton scope in Spring在 Spring 中修改具有单例范围的 bean 的属性
【发布时间】:2017-06-14 14:51:29
【问题描述】:

我有一个单例范围的 bean,如下所示:

public class MyImpl implements MyInterface {

    private HashMap<String, String> config = new HashMap<>();


    private void load(String check) {
        if ("abc".equalsIgnoreCase(check)) {
            config.put("key", "val");
        }
        else {
            config.put("key", "val_else");
        }
    }

    @Override
    public HashMap<String, String> getConfig(String check) {
        load(check);
        return config;
    }
}

然后在其他类中,我注入 MyImpl 并尝试使用如下配置:

  @Service
  public class Service {
    @Inject
    MyInterface impl;
    public doJob(String check){
      HashMap<String, String> config = impl.getConfig(check);
      String myValue= config.get("key");
      //some other code
    }
   }

如果我每秒有 100 次请求,如果 check 的值对于某些请求是 abc 而对于其他请求是 some else ,我在 myValue 中的价值是否仍然不同?我试图概括代码,因为我不能在这里分享确切的代码。我的问题是我们可以根据请求修改单例 bean 的属性吗?

【问题讨论】:

    标签: java spring scope singleton


    【解决方案1】:

    创建一个 ThreadLocal 存储(请参阅the example)以避免该问题。

    或者,您可以将 bean 范围更改为 REQUEST

    【讨论】:

      猜你喜欢
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多