How to Inject a Map Using the @Value Spring Annotation

Inject values into map using spring annotation

If you have the following beans in your Spring context:

@Component("category")
class Category extends Cache { }

@Component("attr")
class Attr extends Cache { }

@Component("country")
class Country extends Cache { }

Note that there's no need to explicitly set scope to singleton, since this is the default in Spring. Besides, there's no need to use @Qualifier; it's enough to set the bean name via @Component("beanName").

The most simple way to inject singleton bean instances to a map is as follows:

@Autowired
Map<String, Cache> map;

This will effectively autowire all subclasses of Cache to the map, with the key being the bean name.

Injecting values into Hashmap using java Spring

Mapping properties directly into bean fields only support simple basic mappings between properties and field values.

Using a configuration object gives more options and can do this kind of tricks and is also more readable.

https://www.baeldung.com/configuration-properties-in-spring-boot

Spring Annotations - Injecting Map of Objects

1.Inject a Map which contains Objects, (Using Java Config)

You can do like this...

@Configuration
public class MyConfiguration {
@Autowired private WhiteColourHandler whiteColourHandler;

@Bean public Map<ColourEnum, ColourHandler> colourHandlers() {
Map<ColourEnum, ColourHandler> map = new EnumMap<>();
map.put(WHITE, whiteColourHandler);
//put more objects into this map here
return map;
}
}

====================

2.Inject a Map which contains Strings (Using properties file)

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

For example, below property in the properties file.

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

In your code,

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

Note: 1.The hashtag as part of the annotation.

    2.Values must be quotes, else you will get SpelEvaluationException

How to inject a key-value map with Spring 4?

Found a nice feature:

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

inject it anywhere as follows:

@Resource(name = "credit")
private Properties credit;


Related Topics



Leave a reply



Submit