Reputation: 86637
I have a keyvalue properties file that contains error codes and their error messages.
I'd like to inject this file on application startup, so that I can make lookups on the injected property without having to read the file.
The following is just pseudocode, is there anything in Spring
that could create this setup?
@Value(location = "classpath:app.properties")
private Properties props;
whereas app.properties contains:
error1=test
error2=bla
...
If not, how could I achieve this without spring?
Upvotes: 2
Views: 1330
Reputation: 86637
Thanks to the help of "kocko", the following setup works as expected, only annotation config:
@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 should not be provided as a bean, but simply be loaded inside a @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();
}
}
Upvotes: 1
Reputation: 1261
@M Sach You can also use property location instead locations, so you don't have to use list
Upvotes: 0
Reputation: 34424
i am doing it this way 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 like below
<property name="testProperty" value="${testProperty}" />
Upvotes: 0
Reputation: 62854
You can first declare the properties files as a such, by using <util:properties>
in your Spring configuration:
<util:properties id="messages" location="classpath:app.properties" />
This registers a bean with name messages
, which you can autowire/inject in other beans.
@Autowired
@Qualifier("messages")
private Properties props;
More info:
Upvotes: 2