在Spring属性文件中转义属性引用

18

我希望逃避我的Spring属性文件以获取我的bean属性:${ROOTPATH}/relativePath

我有一个简单的Spring配置文件,其中包含:

<context:property-placeholder location="classpath:myprops.properties" />

<bean id="myBean" class="spring.MyBean">
    <property name="myProperty" value="${myproperty}" />
</bean> 

myprops.properties 包含:

myproperty=\${ROOTPATH}/relativePath

上述设置返回:无法解析占位符 'ROOTPATH'。我尝试了很多可能的语法,但没有找到正确的方法。

4个回答

18

使用#{'$'}{myproperty}代替${myproperty}。只需将$替换为#{'$'}


不行,它会被解析为${myproperty}注入到myBean.myProperty中,而不是${ROOTPATH}/relativePath - t7tran
取决于你想要实现什么。我猜你需要将它字面上作为值放到myProperty中。 如果你想从某个地方解析ROOTPATH,例如系统属性,你可以使用Spring表达式语言SpEl。例如像这样: #{ systemProperties['ROOTPATH'] }/relativePath - user2428804

6

目前似乎无法避免使用${},但您可以尝试以下配置来解决问题。

dollar=$

myproperty=${dollar}{myproperty}

在评估后,${myproperty}将成为我的属性的结果。


看起来很漂亮,但对我没用。dollar=#{'$'}有效。 - Hawk

3

这里是一个Spring的工单,要求提供转义支持(截至撰写本文时仍未解决)。

暂时的解决办法是使用

$=$
myproperty=${$}{ROOTPATH}/relativePath

虽然提供了解决方案,但看起来相当混乱。

使用SPEL表达式,如#{'$'}在Spring Boot 1.5.7中对我无效。


0

虽然它能工作,但转义占位符的方式非常丑陋。

我通过重写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."))检查。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接