如何使用Spring注入keyvalue属性文件?

我有一个keyvalue属性文件,其中包含错误代码及其错误消息。

我想在应用程序启动时注入此文件,以便我可以在注入的属性上进行查找而无需读取文件。

以下只是伪代码, Spring中有什么可以创建这个设置吗?

 @Value(location = "classpath:app.properties") private Properties props; 

而app.properties包含:

 error1=test error2=bla ... 

如果没有,如果没有弹簧我怎么能实现这个目标

您可以首先在Spring配置中使用声明属性文件:

  

这会在bean上注册名称messages ,您可以在其他bean中自动assembly/注入。

 @Autowired @Qualifier("messages") private Properties props; 

更多信息:

  • Spring中的架构

感谢“kocko”的帮助,以下设置按预期工作,只有注释配置:

 @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提供,而只是在@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(); } } 

我在我的项目中这样做

     classpath:myApplication.properties    

然后使用下面的属性

  

@M Sach您还可以使用属性位置代替位置,因此您不必使用列表