'How to use properties value as fixed value map at spring framework?

I have to mapping properties value as public static immutable Map.

I googling hard n have been try many solution to my code, but they always return null.

I try many way but nothing works for me..

 

Example Code

// 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);
  }
}

My first try : Use static block

/// TestMap(HashMap) up here

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

My first fail. I realized @Value annotation created at Runtime. so I try another way.

 

My second fail : singleton & instance block

/// 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());
  ....
}

And It still return null and now I'm starting very confuse.

I thought instance block will be created after instance got initialize. so @Value will be excute at instance block. (therefore @Value annotation mapping properties value)

So I thought this code will be operate without any problem.

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

but it still return null.

Did I misunderstanding about instance and static?

or I using wrong way to mapping properties value as immutable?

I also try another way to load value at map(caching, another method ....) but it not that satisfied.



Solution 1:[1]

Have a look at @Component and @Autowired annotations. You can annotate your Testone class with @Component and inject it in the Testone testone object, rather than creating the new object of the Testone class.

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

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

And

@Autowired
TestOne testOne

hashMap.put(1, testOne);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naresh Sharma