Search code examples
javaspringdependency-injectionannotationsspring-annotations

How to inject a Map using the @Value Spring Annotation?


How can I inject values into a Map from the properties file using the @Value annotation in Spring?

My Spring Java class is and I tried using the $, but got the following error message:

Could not autowire field: private java.util.Map Test.standard; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'com.test.standard' in string value "${com.test.standard}"

@ConfigurationProperty("com.hello.foo")
public class Test {

   @Value("${com.test.standard}")
   private Map<String,Pattern> standard = new LinkedHashMap<String,Pattern>

   private String enabled;

}

I have the following properties in a .properties file

com.test.standard.name1=Pattern1
com.test.standard.name2=Pattern2
com.test.standard.name3=Pattern3
com.hello.foo.enabled=true

Solution

  • I believe Spring Boot supports loading properties maps out of the box with @ConfigurationProperties annotation.

    According that docs you can load properties:

    my.servers[0]=dev.bar.com
    my.servers[1]=foo.bar.com
    

    into bean like this:

    @ConfigurationProperties(prefix="my")
    public class Config {
    
        private List<String> servers = new ArrayList<String>();
    
        public List<String> getServers() {
            return this.servers;
        }
    }
    

    I used @ConfigurationProperties feature before, but without loading into map. You need to use @EnableConfigurationProperties annotation to enable this feature.

    Cool stuff about this feature is that you can validate your properties.