javaspringescapingyamlspring-el

How to escape SpEL dollar signs in Spring YAML configuration?


In a Spring YAML configuration file, I need to have a parameter like

csv:
  file:
    pattern: /some/path/${app-name}.csv

where the ${app-name} is dynamically replaced in run time by the Java code, and I do not want Spring to replace it at the startup.

To achieve this, I need to escape the $ character so Spring does not interpret it as SpEL.

The following answers do not work in YAML:

I tried all the combinations, like

pattern: /some/path/\${app-name}.csv
pattern: "/some/path/\${app-name}.csv"
pattern: /some/path/#{'$'}{app-name}.csv
pattern: "/some/path/#{'$'}{app-name}.csv"

and none of them produces the variable containing the requested string, with the dollar sign but without the escape characters.

Please notice that it is YAML configuration. In YAML files, # is the line comment character, everything from this character on is ignored. And if I use \#, the \ is then passed to the string.

ADDED: There has been an Spring project open issue 9628 open since 25.06.2008:

There is presently no way to inject a ${...} expression that won't be picked up by PropertyPlaceholderConfigurer. Ideally we should be able to inject a string that contains ${...} for later use in its target bean without involvement from PropertyPlaceholderConfigurer.


Solution

  • Spring currently does not offer an escaping mechanism for property placeholders, there is an open issue (opened on 25.06.2008):

    There is presently no way to inject a placeholder expression (${...})

    In the comments, this workaround is mentioned (I am not sure whether it works with YAML):

    csv:
      file:
        pattern: /some/path/#{'$'}{app-name}.csv
    

    Note that when used after whitespace or at the beginning of a line, # in YAML starts a comment.