How to escape SpEL dollar signs in Spring YAML configuration?

Honza Zidek picture Honza Zidek · Dec 21, 2017 · Viewed 10.4k times · Source

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.

Answer

I had the same problem, i just found dumb clever solution define a property named dollarSign or ds for short.

ds: "$"

then use it like so, ${ds} will be replace by $ at runtime.

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

it was kind of funny when it worked.