Java Spring 中的动态 @Value 等效项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21276701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:50:04  来源:igfitidea点击:

Dynamic @Value-equivalent in Spring?

javaspringproperties-file

提问by Doches

I have a Spring-managed bean that loads properties using a property-placeholderin its associated context.xml:

我有一个 Spring 管理的 bean,property-placeholder它在其关联的 中使用 a 加载属性context.xml

<context:property-placeholder location="file:config/example.prefs" />

I can access properties using Spring's @Valueannotations at initialisation, e.g.:

我可以@Value在初始化时使用 Spring 的注释访问属性,例如:

@Value("${some.prefs.key}")
String someProperty;

...but I need to expose those properties to other (non-Spring managed) objects in a generic way. Ideally, I could expose them through a method like:

...但我需要以通用方式将这些属性公开给其他(非 Spring 管理的)对象。理想情况下,我可以通过以下方法公开它们:

public String getPropertyValue(String key) {
  @Value("${" + key + "}")
  String value;

  return value;
}

...but obviously I can't use the @Valueannotation in that context. Is there some way I can access the properties loaded by Spring from example.prefsat runtime using keys, e.g.:

...但显然我不能@Value在这种情况下使用注释。有什么方法可以example.prefs在运行时使用键访问 Spring 加载的属性,例如:

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

回答by Sangam Belose

Autowire the Environment object in your class. Then you will be able to access the properties using environment.getProperty(propertyName);

自动装配类中的 Environment 对象。然后您将能够使用 environment.getProperty(propertyName); 访问属性。

@Autowired
private Environment environment;

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

Also add @PropertySource on Config class.

还要在 Config 类上添加 @PropertySource。

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

回答by Wilson Campusano

inject BeanFactory into your bean.

将 BeanFactory 注入到你的 bean 中。

 @Autowired
 BeanFactory factory;

then cast and get the property from the bean

然后投射并从 bean 中获取属性

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