我正在尝试从 Spring 的 Environment property abstraction 动态访问属性.
我这样声明我的属性文件:
<context:property-placeholder
location="classpath:server.common.properties,
classpath:server.${my-environment}.properties" />
在我的属性文件 server.test.properties
中,我定义了以下内容:
myKey=foo
然后,给定以下代码:
@Component
public class PropertyTest {
@Value("${myKey}")
private String propertyValue;
@Autowired
private PropertyResolver propertyResolver;
public function test() {
String fromResolver = propertyResolver.getProperty("myKey");
}
}
当我运行这段代码时,我以 propertyValue='foo'
结束,但是 fromResolver=null
;
接收 propertyValue
表示正在读取属性(我从代码的其他部分知道这一点)。但是,尝试动态查找它们是失败的。
为什么?如何在不使用 @Value
的情况下动态查找属性值?
最佳答案
只需添加一个 <context:property-placeholder/>
不会向环境添加新的 PropertySource。如果您完整阅读了链接的文章,您会看到它建议注册 ApplicationContextInitializer
为了添加新的 PropertySources,以便它们以您尝试使用它们的方式可用。
关于java - 使用 Spring 3.1 的属性抽象动态访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705042/