Java Spring属性资源占位符配置器bean:在运行时解析属性值
我正在加载具有多个Java Spring属性资源占位符配置器bean:在运行时解析属性值,java,spring,properties,spring-properties,Java,Spring,Properties,Spring Properties,我正在加载具有多个propertysourcesplaceplaceconfigurerbean的属性,并设置占位符前缀es: @Bean public static PropertySourcesPlaceholderConfigurer fooPropertyConfigurer() { PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlac
propertysourcesplaceplaceconfigurer
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”)的值,并动态解析属性值。这可能吗?如果没有,建议针对该用例使用哪些替代解决方案?多亏了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");
}