Search code examples
javaspringspring-el

How to get raw value of property containing placeholders?


I am trying to define the following property in one of my .properties files:

personExpression=${person.surname}

This is then read by a config class:

@Configuration
public class TemplateConfig {
    @Autowired
    private Environment environment;

    public String getPersonExpression() {
        return environment.getProperty("personExpression");
    }
}

However this gives the exception:

java.lang.IllegalArgumentException: Could not resolve placeholder 'person.surname' in string value "${person.surname}"

Is there a way to do get getPersonExpression() to return the string literal ${person.surname} without attempting to resolve it?


Solution

  • To get this to work takes some pretty unintuitive syntax.

    You essentially have to split your expression into two parts and wrap the whole thing in a parent SpEL expression to join them.

    If you change your property value to the following it should work:

    personExpression=#{'$' + '{person.surname}'}
    

    This works because you're splitting up the $ character from the {person.surname} so SpEL won't try to evaluate it as an expression, because as far as it's concerned, you're just concatenating two strings together.