I am trying to load come properties from config using the Spring @Configuration & @ConfigurationProperties combination. I have a POJO that extends HashMap<Integer, String> and has a single variable inside. (See MyConfigPojo
below). From the .yaml file, I have the same shape. However, when booting up the app, I get an error when trying to parse the string for the defaultValue into an Integer.
@Configuration
@ConfigurationPropeties(prefix = "my-config")
public class MyConfigPojo extends HashMap<Integer, String> {
private String defaultValue;
private String getValueForIdOrDefault(int id); // this.get(id) OR ELSE defaultValue
}
In config I have this:
myConfig:
1: "my first value"
23: "my 23rd value"
defaultValue: "cheese"
Which results in a
APPLICATION FAILED TO START
Description:
Failed to bind properties under 'myPackage' to MyConfigPojo:
Property: myConfig[1]
Value: cheese
I thought that was weird, so I turned on TRACE logs and found this:
99 common frames omittedCaused by: java.lang.NumberFormatException: For input string: "defaultValue" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
Is there a way to intercept reading this file or to tell Spring how to set the values properly?
You are trying to read a Map from .yml file, for that, you need
@ConfigurationProperties
annotation enough, don't need@Configuration
annotation(if using spring boot). If you are using spring-framework, you need @Configuration also.Use this example:
MyConfigPojo.java
Now, you can Autowire this
MyConfigPojo
class anywhere(for instance, in controller class) and read those map keys and values.Now, you have considered keys & Values as
String
datatype for that Map, you will not getNumberFormatException
.