我有一个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
注释。有没有办法在运行时使用密钥从example.prefs
访问Spring加载的属性,例如:
public String getPropertyValue(String key) {
return SomeSpringContextOrEnvironmentObject.getValue(key);
}
答案 0 :(得分:6)
在您的班级中自动装配Environment对象。然后,您将能够使用environment.getProperty(propertyName);
访问这些属性@Autowired
private Environment environment;
// access it as below wherever required.
environment.getProperty(propertyName);
在Config类上添加@PropertySource。
@Configuration
@PropertySource("classpath:some.properties")
public class ApplicationConfiguration
答案 1 :(得分:0)
将BeanFactory注入您的bean。
@Autowired
BeanFactory factory;
然后施放并从bean获取属性
((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")