【问题标题】:Dynamic @Value-equivalent in Spring?Spring中的动态@Value等价物?
【发布时间】:2014-02-12 03:26:23
【问题描述】:

我有一个 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 注释。有什么方法可以让我在运行时使用键访问 Spring 从example.prefs 加载的属性,例如:

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

【问题讨论】:

  • 我想这就是你要找的东西:stackoverflow.com/questions/1771166/…
  • 我将创建一个正常的 bean,它将 spring bean 作为 contrucotr 参数,spring bean 的值已经设置,因为它是由 spring 实例化的。我想这在某种程度上取决于您的架构。
  • 你能告诉我们更多关于你所谓的“非 Spring 托管”的信息
  • 当然——一个没有被 Spring 实例化的类,我无法直接访问 Spring ApplicationContext。我所说的“非 Spring 托管”的意思是“没有从 XML 实例化为 bean。”

标签: java spring properties-file


【解决方案1】:

在你的类中自动装配 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

【讨论】:

【解决方案2】:

将 BeanFactory 注入您的 bean。

 @Autowired
 BeanFactory factory;

然后强制转换并从 bean 中获取属性

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

【讨论】:

  • 使用 Spring Boot 2.2.7-RELEASE,您应该 @Autowire ConfigurableBeanFactory 而不是 BeanFactory。实际上,如果您 @Autowire Bean Factory,它会抱怨 NullPointerException
  • 顺便说一句,在成员级别使用 Autowire 会抛出一个警告,如果您在 setter 或构造函数中使用 @Autowire,则可以消除该警告。
猜你喜欢
  • 2011-01-05
  • 2013-01-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
相关资源
最近更新 更多