簡體   English   中英

Spring PropertySourcesPlaceholderConfigurer beans:在運行時解析屬性值

[英]Spring PropertySourcesPlaceholderConfigurer beans: resolve property value at runtime

我正在使用多個PropertySourcesPlaceholderConfigurer bean 加載屬性並設置占位符前綴:

@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') 的值並動態解析屬性值。 這可能嗎? 如果不是,那么針對此用例推薦哪些替代解決方案?

感謝這篇文章,我找到了一個解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM