虽然它有效,但逃避占位符是超级丑陋的。
我实现了我的覆盖PropertySourcesPlaceholderConfigurer.doProcessProperties
并使用自定义StringValueResolver
public static class CustomPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
@Override
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess, StringValueResolver valueResolver) {
StringValueResolver customValueResolver = strVal -> {
if(strVal.startsWith("${something.")) {
PropertySourcesPropertyResolver customPropertySourcesPropertyResolver = new PropertySourcesPropertyResolver(this.getAppliedPropertySources());
String resolvedText = customPropertySourcesPropertyResolver.resolvePlaceholders(strVal);
//remove the below check if you are okay with the property not being present (i.e remove if the property is optional)
if(resolvedText.equals(strVal)) {
throw new RuntimeException("placeholder " + strVal + " not found");
}
return resolvedText;
}
else {
//default behaviour
return valueResolver.resolveStringValue(strVal);
}
};
super.doProcessProperties(beanFactoryToProcess, customValueResolver);
}
}
将其插入应用程序
@Configuration
public class PlaceHolderResolverConfig
{
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
PropertySourcesPlaceholderConfigurer placeHolderConfigurer = new CustomPropertySourcesPlaceholderConfigurer();
placeHolderConfigurer.setLocation(new ClassPathResource("application.properties"));
return placeHolderConfigurer;
}
}
在上面的示例中,对于所有以嵌套占位符开头的属性都something.*
不会被解析..if(strVal.startsWith("${something."))
如果您想要所有属性的行为,请删除检查