gpt4 book ai didi

java - Spring中的动态@Value等价物?

转载 作者:IT老高 更新时间:2023-10-28 13:47:11 24 4
gpt4 key购买 nike

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

<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);
}

最佳答案

在你的类中 Autowiring 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

关于java - Spring中的动态@Value等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21276701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com