春季的动态@Value等效?

2022-09-03 13:52:05

我有一个Spring管理的bean,它在其关联中使用a来加载属性:property-placeholdercontext.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;
}

...但显然我不能在那种情况下使用注释。有没有办法使用键从运行时访问Spring加载的属性,例如:@Valueexample.prefs

public String getPropertyValue(String key) {
  return SomeSpringContextOrEnvironmentObject.getValue(key);
}

答案 1

自动连接类中的环境对象。然后,您将能够使用 environment.getProperty(propertyName) 访问属性;

@Autowired
private Environment environment;

// access it as below wherever required.
 environment.getProperty(propertyName);

还要在配置类上添加@PropertySource。

@Configuration
@PropertySource("classpath:some.properties")
public class ApplicationConfiguration

答案 2

将BeanFactory注入您的Bean。

 @Autowired
 BeanFactory factory;

然后铸造并从豆子中获取属性

((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")

推荐