1

Given a class like:

@Component
public class ValueHelper {

    private static Map<Integer, Number> valuesMap;
    static {
        valuesMap = new HashMap<>();
        valuesMap.put(11, Short.parseShort("0"));
        valuesMap.put(12, Integer.valueOf(0));
        valuesMap.put(21, Float.NaN);
        valuesMap.put(22, Double.NaN);
        valuesMap.put(14, Long.valueOf(0L));
    }

    public Number getFillValueForType(Integer key) {
        Number number = valuesMap.get(key);
        return number;
    }
}

I don't like this static initialisation and wanted to know if there is a better way to do it in Spring Boot using the application.properties. I've seen that there is basic support for maps via application.properties but it doesn't seem complex enough to handle objects in this way?

If not possible via properties, maybe there is a way to avoid this static initialisation in any case.

Thanks

user1472672
  • 313
  • 1
  • 9

1 Answers1

2

Using @ConfigurationProperties you can inject them into Map<Integer,Number>

@ConfigurationProperties("test")
@Data
@Configuration
public class TestConfig {

    private Map<String,Number> values;

    public Number getFillValueForType(Integer key) {
        Number number = values.get(key);
        return number;
    }
}

application.yml

test:
  values:
    11: 0
    12: 0
    21: 0
    22: 0
    14: 0
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98