2

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.

2
  • 1
    myMap will be loaded as a String not a map Commented Aug 24, 2018 at 13:56
  • Try using the interface Map not the implementation HashMap Commented Aug 24, 2018 at 14:03

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the details. It seems that there is no straight cut way to get a map out of environment API. I had to take that string, then remove curly braces, then remove apostrophe sign and then split the string to fetch out key-value pairs and then put them in map. Whoo... Thanks for suggestions.
-1

Don't think too much just check your pojo class. Getting value from database is different , field from pojo class is different.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.