如何使用Spring注入keyvalue属性文件? [英] How to inject a keyvalue properties file with Spring?
问题描述
我有一个keyvalue属性文件,其中包含错误代码及其错误消息。
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.
以下只是伪代码, Spring中有什么东西
那可以创建这个设置吗?
The following is just pseudocode, is there anything in Spring
that could create this setup?
@Value(location = "classpath:app.properties")
private Properties props;
而app.properties包含:
whereas app.properties contains:
error1=test
error2=bla
...
如果没有,我怎么能在没有弹簧的情况下实现这个目标?
If not, how could I achieve this without spring?
推荐答案
感谢kocko的帮助,以下设置按预期工作,只有注释配置:
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;
或者,如果资源不应该作为bean提供,而只是在<$ c中加载$ c> @Component :
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();
}
}
这篇关于如何使用Spring注入keyvalue属性文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!