我有一个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);
}
在类中自动装配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
将BeanFactory注入到bean中。
@Autowired
BeanFactory factory;
然后施放并从豆中获取属性
((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")