如何解决Spring PropertySourcesPlaceholderConfigurer Bean:在运行时解析属性值
我正在使用多个PropertySourcesPlaceholderConfigurer
bean加载属性并设置占位符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;
}
虽然我可以通过如下指定属性的索引和键来注入属性值:
@Value("$foo{key}")
private String value;
有时我需要在运行时确定前缀('foo')的值并动态解析属性值。这可能吗?如果不是,那么针对此用例推荐哪种替代解决方案?
解决方法
感谢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");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。