How do I get a property value from an ApplicationContext object? (not using an annotation)

流过昼夜 提交于 2019-11-28 22:24:31

In the case where SPeL expression needs to be dynamic, get the property value manually:

somePropValue = ctx.getEnvironment().getProperty("someProp");

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.

A solution would be to create some sort of a value holder bean that you initialize with the property / properties you need.

@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

If you are stuck on Spring pre 3.1, you can use

somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!