Spring中的Dynamic @ Value等价?

问题描述 投票:9回答:2

我有一个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);
}
java spring properties-file
2个回答
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

0
投票

将BeanFactory注入到bean中。

 @Autowired
 BeanFactory factory;

然后施放并从豆中获取属性

((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")
© www.soinside.com 2019 - 2024. All rights reserved.