How to insert a key value properties file using Spring?
I have a key value properties file containing error codes and their error messages.
I would like to add this file when I start the application so that I can search on the attached property without having to read the file.
Below is the pseudocode, is there anything in Spring
that could create this setting?
@Value(location = "classpath:app.properties")
private Properties props;
whereas app.properties contains:
error1=test error2=bla ...
If not, how can I achieve this without spring?
source to share
Thanks to the help of "kocko", the following setup works as expected only with the annotation configuration:
@Bean(name = "errors")
public PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("errors.properties"));
return bean;
}
@Resource(name = "errors")
private Properties errors;
Or if the resource is not supposed to be exposed as a bean, but simply loaded internally @Component
:
@Component
public class MyLoader {
private Properties keys;
@PostConstruct
public void init() throws IOException {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("app.properties"));
bean.afterPropertiesSet();
keys = bean.getObject();
}
}
source to share
You can first declare the properties files as such using <util:properties>
in your Spring config:
<util:properties id="messages" location="classpath:app.properties" />
This registers a bean with a name messages
that you can autowire / inject into other beans.
@Autowired
@Qualifier("messages")
private Properties props;
Additional Information:
source to share
I do it like this in my project
<bean id="myPropertyHolder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:myApplication.properties</value>
</list>
</property>
</bean>
Then use the property as shown below
<property name="testProperty" value="${testProperty}" />
source to share