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

前端 未结 3 966
一生所求
一生所求 2020-12-14 14:18

If I have:

@Autowired private ApplicationContext ctx;

I can get beans and resources by using one of the the getBean methods. However, I can

相关标签:
3条回答
  • 2020-12-14 14:34

    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

    0 讨论(0)
  • 2020-12-14 14:45

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

    somePropValue = ctx.getEnvironment().getProperty("someProp");
    
    0 讨论(0)
  • 2020-12-14 14:45

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

    somePropValue = ctx.getBeanFactory().resolveEmbeddedValue("${someProp}");
    
    0 讨论(0)
提交回复
热议问题