【发布时间】:2014-02-12 03:26:23
【问题描述】:
我有一个 Spring 管理的 bean,它使用 property-placeholder 在其关联的 context.xml 中加载属性:
<context:property-placeholder location="file:config/example.prefs" />
我可以在初始化时使用 Spring 的 @Value 注释访问属性,例如:
@Value("${some.prefs.key}")
String someProperty;
...但我需要以通用方式将这些属性公开给其他(非 Spring 管理的)对象。理想情况下,我可以通过以下方法公开它们:
public String getPropertyValue(String key) {
@Value("${" + key + "}")
String value;
return value;
}
...但显然我不能在那种情况下使用@Value 注释。有什么方法可以让我在运行时使用键访问 Spring 从example.prefs 加载的属性,例如:
public String getPropertyValue(String key) {
return SomeSpringContextOrEnvironmentObject.getValue(key);
}
【问题讨论】:
-
我想这就是你要找的东西:stackoverflow.com/questions/1771166/…
-
我将创建一个正常的 bean,它将 spring bean 作为 contrucotr 参数,spring bean 的值已经设置,因为它是由 spring 实例化的。我想这在某种程度上取决于您的架构。
-
你能告诉我们更多关于你所谓的“非 Spring 托管”的信息
-
当然——一个没有被 Spring 实例化的类,我无法直接访问 Spring ApplicationContext。我所说的“非 Spring 托管”的意思是“没有从 XML 实例化为 bean。”
标签: java spring properties-file