103

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
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
yathirigan
  • 5,619
  • 22
  • 66
  • 104
  • You will need to use spring expression language. A similar question which used list (https://stackoverflow.com/questions/27390363/spring-how-to-inject-an-inline-list-of-strings-using-value-annotation). I am not sure you can do what you want out of the box. This question https://stackoverflow.com/questions/28369458/how-to-fill-hashmap-from-java-property-file-with-spring-value is a bit more to your point. Uses a custom property mapper – Laurentiu L. Jun 07 '15 at 09:46
  • What exactly do you want in your map? It seems you also expect some type converstion to a `Pattern`? What kind of `Pattern` class is that? – K Erlandsson Jun 07 '15 at 09:48
  • @Erlandsson this is a RegEx pattern, we will define valid regex pattern strings in the value – yathirigan Jun 07 '15 at 17:34
  • 1
    @LaurentuiL uin Spring boot, i am able to directly inject a map if the map matches the prefix described at class level but,my problem is the prefix at class level and this attribute level is different – yathirigan Jun 07 '15 at 17:51

8 Answers8

188

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

Stijn Van Bael
  • 4,830
  • 2
  • 32
  • 38
Michael Rahenkamp
  • 1,881
  • 2
  • 10
  • 2
24

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.

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
  • yes but, my problem is.. The Test class has its own @ConfigurationProperties prefix. So i want to use a diff prefix for this member variable alone . how can i do that ? – yathirigan Jun 07 '15 at 17:37
  • 1
    hmm, I missed that. So I would create separate two beans with @ConfiguraitonProperties annotation and autowire them into test class. – luboskrnac Jun 07 '15 at 17:53
  • may have worked for the OP, but question didn't specify boot, and this problem doesn't work for general Spring, without boot. – xenoterracide Dec 13 '16 at 22:40
  • 13
    the question is how to inject to a map using @Value annotation, but you are telling all sort of things rather than giving the answer to the question. Alternatives are okay but please stick to the answer as well – Mukul Anand Jun 25 '18 at 12:33
21

I had a simple code for Spring Cloud Config

like this:

In application.properties

spring.data.mongodb.db1=mongodb://test@test1.com

spring.data.mongodb.db2=mongodb://test@test2.com

read

@Bean(name = "mongoConfig")
@ConfigurationProperties(prefix = "spring.data.mongodb")
public Map<String, Map<String, String>> mongoConfig() {
    return new HashMap();
}

use

@Autowired
@Qualifier(value = "mongoConfig")
private Map<String, String> mongoConfig;

@Bean(name = "mongoTemplates")
public HashMap<String, MongoTemplate> mongoTemplateMap() throws UnknownHostException {
    HashMap<String, MongoTemplate> mongoTemplates = new HashMap<>();
    for (Map.Entry<String, String>> entry : mongoConfig.entrySet()) {
        String k = entry.getKey();
        String v = entry.getValue();
        MongoTemplate template = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI(v)));
        mongoTemplates.put(k, template);
    }
    return mongoTemplates;
}
Community
  • 1
  • 1
liuxun
  • 241
  • 2
  • 4
  • 1
    I think your definition for the bean mongoConfig is incorrect. The method should be defined like this. public Map mongoConfig() { return new HashMap(); } – rslj Jul 05 '19 at 14:19
  • this is probably the most elegant way if you simply want to inject a map from application.yml – Agoston Horvath Jan 16 '20 at 14:55
20

You can inject .properties as a map in your class using @Resource annotation.

If you are working with XML based configuration, then add below bean in your spring configuration file:

 <bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:your.properties"/>
 </bean>

For, Annotation based:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "your.properties"));
        return bean;
}

Then you can pick them up in your application as a Map:

@Resource(name = "myProperties")
private Map<String, String> myProperties;
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
  • We have used Spring Cloud Config server to provide the configurations, hence class path approach might not work. And we don't use XMLs – yathirigan Jun 07 '15 at 17:39
  • @Arpit - Could you please guide me here : https://stackoverflow.com/questions/60899860/spring-spel-expression-language-to-create-map-of-string-and-custom-object? – PAA Mar 28 '20 at 10:40
15

To get this working with YAML, do this:

property-name: '{
  key1: "value1",
  key2: "value2"
}'
wild_nothing
  • 2,845
  • 1
  • 35
  • 47
13

Following worked for me:

SpingBoot 2.1.7.RELEASE

YAML Property (Notice value sourrounded by single quotes)

property:
   name: '{"key1": false, "key2": false, "key3": true}'

In Java/Kotlin annotate field with (Notice use of #) (For java no need to escape '$' with '\')

@Value("#{\${property.name}}")
ShareYourWisdom
  • 131
  • 1
  • 4
7

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
Neil Han
  • 420
  • 5
  • 8
3

You can use below code.

Below code for application.yml

my:
  mapValues:
    dbData: '{
      "connectionURL": "http://tesst:3306",
        "userName": "myUser",
        "password": "password123"
    }'

to access these key and values using @Value annotation use below java code.

@Value("#{${my.mapValues.dbData}}")
private Map<String,String> dbValues;
Harsh
  • 2,893
  • 29
  • 16