How to inject a Map using the @Value Spring Annotation?
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.
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.commy.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.
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;