spring 如何从 ApplicationContext 对象中获取属性值?(不使用注释)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10822951/
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
How do I get a property value from an ApplicationContext object? (not using an annotation)
提问by HappyEngineer
If I have:
如果我有:
@Autowired private ApplicationContext ctx;
I can get beans and resources by using one of the the getBean methods. However, I can't figure out how to get property values.
我可以使用 getBean 方法之一来获取 bean 和资源。但是,我无法弄清楚如何获取属性值。
Obviously, I can create a new bean which has an @Value property like:
显然,我可以创建一个具有 @Value 属性的新 bean,例如:
private @Value("${someProp}") String somePropValue;
What method do I call on the ApplicationContext object to get that value without autowiring a bean?
在不自动装配 bean 的情况下,我在 ApplicationContext 对象上调用什么方法来获取该值?
I usually use the @Value, but there is a situation where the SPeL expression needs to be dynamic, so I can't just use an annotation.
我通常使用@Value,但有一种情况,SPeL 表达式需要是动态的,所以我不能只使用注释。
回答by Italo Borssatto
In the case where SPeL expression needs to be dynamic, get the property value manually:
在 SPeL 表达式需要动态的情况下,手动获取属性值:
somePropValue = ctx.getEnvironment().getProperty("someProp");
回答by Sean Patrick Floyd
Assuming that the ${someProp}property comes from a PropertyPlaceHolderConfigurer, that makes things difficult. The PropertyPlaceholderConfigurer is a BeanFactoryPostProcessor and as such only available at container startup time. So the properties are not available to a bean at runtime.
假设该${someProp}属性来自 PropertyPlaceHolderConfigurer,这会让事情变得困难。PropertyPlaceholderConfigurer 是一个 BeanFactoryPostProcessor,因此仅在容器启动时可用。因此,这些属性在运行时对 bean 不可用。
A solution would be to create some sort of a value holder bean that you initialize with the property / properties you need.
一个解决方案是创建某种类型的值持有者 bean,您可以使用您需要的属性/属性进行初始化。
@Component
public class PropertyHolder{
@Value("${props.foo}") private String foo;
@Value("${props.bar}") private String bar;
// + getter methods
}
Now inject this PropertyHolder wherever you need the properties and access the properties through the getter methods
现在在需要属性的任何地方注入这个 PropertyHolder 并通过 getter 方法访问属性
回答by Asa
If you are stuck on Spring pre 3.1, you can use
如果您坚持使用 Spring pre 3.1,则可以使用
somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");

