Skip to content
Advertisement

Spring PropertySourcesPlaceholderConfigurer beans: resolve property value at runtime

I am loading properties with multiple PropertySourcesPlaceholderConfigurer beans and setting placeholder prefix-es:

@Bean
public static PropertySourcesPlaceholderConfigurer fooPropertyConfigurer() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("foo.properties"));
    propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true);
    propertySourcesPlaceholderConfigurer.setPlaceholderPrefix("$foo{");
    return propertySourcesPlaceholderConfigurer;
}

While I can inject a property value by specifying it’s index and key like this:

@Value("$foo{key}")
private String value;

Sometimes I need to determine the value of the prefix (‘foo’) at runtime and dynamically resolve the property value. Is this possible? If not, which alternative solutions are recommended for this use case?

Advertisement

Answer

Thanks to this post, I’ve found a solution:

@Component
public class PropertyPlaceholderExposer implements BeanFactoryAware {  
    
    ConfigurableBeanFactory beanFactory; 

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = (ConfigurableBeanFactory) beanFactory;
    }

    public String resolveProperty(String prefix, String key) {
        String rv = beanFactory.resolveEmbeddedValue("$" + prefix + "{" + key + "}");
        return rv;
    }

}

Usage:

@Autowired
private PropertyPlaceholderExposer ppe;
    
{
    String v = ppe.resolveProperty("bar", "key");
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement