I have below code and issue. I am running a Spring boot application to test application.properties file usage.
application.properties file,
server.port=8080
server.servlet.context-path=/HelloWorldBoot
myMap={key1:'value1',key2:'value2'}
Controller code below,
@RestController
public class MyController {
@Autowired
Environment env;
@Value("#{${myMap}}")
private HashMap<String,String> myMapUsingValue;
@GetMapping("/hello")
public String hello() {
System.out.println("myMapUsingValue : "+myMapUsingValue);
HashMap<String, String> myMapUsingEnv = env.getProperty("myMap", HashMap.class);
System.out.println("myMapUsingEnv : "+myMapUsingEnv);
return "Hello World";
}
}
Now when I hit the URL: http://localhost:8080/HelloWorldBoot/hello
Map details using @Value gets printed successfully,
myMapUsingValue : {key1=value1, key2=value2}
But I get error like below while accessing the same Map using Environment API,
No converter found capable of converting from type [java.lang.String] to type [java.util.HashMap<?, ?>]]
How can I resolve this? How can I read the Map directly from application properties file using the Environment variable API?
Any help is appreciated on this. Thanks in advance.
Environment variables are always strings. The fact that the Spring value injector knows how to convert them to a map is super nice, but when using the java environment api you are going to have to parse that string yourself and convert it into a Map.
Something like Jackson might make this easier. Otherwise you might write a utility method that does this. You might look in the spring source.