Spring PropertySourcesPlaceholderConfigurer bean:在运行时解析 属性 值

Spring PropertySourcesPlaceholderConfigurer beans: resolve property value at runtime

我正在使用多个 PropertySourcesPlaceholderConfigurer bean 加载属性并设置占位符前缀-es:

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

虽然我可以通过指定索引和键来注入 属性 值,如下所示:

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

有时我需要在运行时确定前缀('foo')的值并动态解析属性值。这可能吗?如果不是,针对此用例推荐哪些替代解决方案?

感谢 this post,我找到了解决方案:

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

}

用法:

@Autowired
private PropertyPlaceholderExposer ppe;
    
{
    String v = ppe.resolveProperty("bar", "key");
}