How to insert a properties file using Spring?
How can I insert the following key value file as a variable Properties
or HashMap
directly using spring
?
Src / main / resources / myfile.properties:
key1=test someotherkey=asd (many other key-value pairs)
None of the following worked:
@Value("${apikeys}")
private Properties keys;
@Resource(name = "apikeys")
private Properties keys;
Sidenote: I don't know the keys inside the properties file beforehand. Therefore I cannot use injection @PropertyResource
.
source to share
To use annotation first Value
, you need to define in applicationContext.xml
below bean
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:myfile.properties"></property>
</bean>
Once you define your properties file, you can use annotation Value
.
source to share
One way to achieve this is to create a bean in the config file:
@Bean
public Map<String, String> myFileProperties() {
ResourceBundle bundle = ResourceBundle.getBundle("myfile");
return bundle.keySet().stream()
.collect(Collectors.toMap(key -> key, bundle::getString));
}
Then you can easily inject this bean into your service for example.
@Autowired
private Map<String, String> myFileProperties;
(consider using constructor inset)
Also don't forget
@PropertySource("classpath:myfile.properties")
source to share
You can use PropertySource annotation :
Example:
@PropertySource("myfile.properties")
public class Config {
@Autowired
private Environment env;
@Bean
ApplicationProperties appProperties() {
ApplicationProperties bean = new ApplicationProperties();
bean.setKey1(environment.getProperty("key1"));
bean.setsomeotherkey(environment.getProperty("someotherkey"));
return bean;
}
}
source to share