繁体   English   中英

如何在 spring 框架中使用属性值作为固定值 map?

[英]How to use properties value as fixed value map at spring framework?

我必须将属性值映射为公共 static 不可变 Map。

我用谷歌搜索已经尝试了很多解决我的代码的方法,但它们总是返回 null。

我尝试了很多方法,但对我没有用..

示例代码

// properties

test.value=Hello


public interface TestObject {
  String getValue();
}

@Component
public class TestOne implements TestObject {
  
  @Value(${test.value})
  private String value;

  @Override
  public String getValue() {
    return value;
  }
}

public class TestMap {
  // I wanna load TestObject at here as Map
  private static final Map<Integer, TestObject> hashMap = new HashMap<>();

  public TestObject getTestObject(int num) {
    return hashMap.get(num);
  }
}

我的第一次尝试:使用 static 块

/// TestMap(HashMap) up here

static {
  hashMap.put(1, new TestOne());
  hashMap.put(2, new TestTwo()); // another class what implements TestObject
  ....
}

我的第一次失败。 我意识到在运行时创建的@Value 注释。 所以我尝试另一种方式。

我的第二次失败:singleton & 实例块

/// TestMap(HashMap) up here

static TestMap testMap;

public static TestMap getInstance() {
        if (testMap == null) instance = new TestMap();
        return testMap;
}

{
  hashMap.put(1, new TestOne());
  hashMap.put(2, new TestTwo());
  ....
}

它仍然返回 null,现在我开始很困惑。

我认为实例块将在实例初始化后创建。 所以 @Value 将在实例块中执行。 (因此@Value 注解映射属性值)

所以我认为这段代码可以毫无问题地运行。

TestObject object = TestMap.getInstance().getTestObject(1);
System.out.println(object.getValue());

但它仍然返回 null。

我对实例和 static 有误解吗?

或者我使用错误的方式将属性值映射为不可变?

我还尝试了另一种方法来在地图上加载值(缓存,另一种方法......)但它并不令人满意。

查看@Component@Autowired注释。 你可以用@Component注解你的Testone class并注入Testone testone object,而不是创建Testone class的新Testone

@Component
public class TestOne implements TestObject {
  
  @Value(${test.value})
  private String value;

  @Override
  public String getValue() {
    return value;
  }
}

@Autowired
TestOne testOne

hashMap.put(1, testOne);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM