【问题标题】:Spring PropertySourcesPlaceholderConfigurer beans: resolve property value at runtimeSpring PropertySourcesPlaceholderConfigurer beans:在运行时解析属性值
【发布时间】:2021-02-12 05:28:25
【问题描述】:

我正在加载带有多个 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') 的值并动态解析属性值。这可能吗?如果没有,针对此用例推荐哪些替代解决方案?

【问题讨论】:

    标签: java spring properties spring-properties


    【解决方案1】:

    感谢this 发帖,我找到了解决办法:

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

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 2015-08-01
      相关资源
      最近更新 更多