[java] 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

The answer is


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

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;

To get this working with YAML, do this:

property-name: '{
  key1: "value1",
  key2: "value2"
}'

I had a simple code for Spring Cloud Config

like this:

In application.properties

spring.data.mongodb.db1=mongodb://[email protected]

spring.data.mongodb.db2=mongodb://[email protected]

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;
}

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}}")

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to dependency-injection

Are all Spring Framework Java Configuration injection examples buggy? Passing data into "router-outlet" child components ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why? org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController' How to inject window into a service? How to get bean using application context in spring boot Resolving instances with ASP.NET Core DI from within ConfigureServices How to inject a Map using the @Value Spring Annotation? WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Examples related to annotations

How to inject a Map using the @Value Spring Annotation? intellij incorrectly saying no beans of type found for autowired repository @Autowired - No qualifying bean of type found for dependency Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll Can't find @Nullable inside javax.annotation.* Name attribute in @Entity and @Table Get rid of "The value for annotation attribute must be a constant expression" message @Value annotation type casting to Integer from String What does -> mean in Python function definitions? @Nullable annotation usage

Examples related to spring-annotations

Spring Boot @Value Properties How to inject a Map using the @Value Spring Annotation? @Autowired - No qualifying bean of type found for dependency at least 1 bean Populating Spring @Value during Unit Test Spring MVC @PathVariable with dot (.) is getting truncated Is there a way to @Autowire a bean that requires constructor arguments? What does the @Valid annotation indicate in Spring?