我的 xml 文件中有以下配置:
<util:properties id="apiConfigurator" location="classpath:api.properties" scope="singleton"/>
这是我的属性文件:
appKey=abc
appSecret=def
在我的 Spring 类(class)中,我得到了一些像这样的值:
@Value("#{apiConfigurator['appKey']}")
我想在 Spring 中创建一个 @Configuration
类来解析属性文件,
@Value("#{apiConfigurator['appKey']}")
在我使用它的类(class)中仍然有效。我该如何正确地做到这一点?
最佳答案
当您指定时
<util:properties .../>
Spring 使用您指定的名称/id 注册一个 PropertiesFactoryBean
bean。
你需要做的就是自己提供这样一个@Bean
// it's singleton by default
@Bean(name = "apiConfigurator") // this is the bean id
public PropertiesFactoryBean factoryBean() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("api.properties"));
return bean;
}
关于java - Spring XML+属性配置到Java类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22383740/