Search code examples
spring-bootyamlsnakeyaml

Sping-Boot Config: How to keep whitespace in yaml key being used to populate Map<String, String>


Let's say we have a configuration properties class:

@ConfigurationProperties(prefix = "whitespace.test")
public class WhitespaceTestConfig {

    private Map<String, String> configs;

    public Map<String, String> getConfigs() {
        return configs;
    }

    public void setConfigs(Map<String, String> configs) {
        this.configs = configs;
    }
}

and we try to configure it with a key with space included in it:

whitespace.test.configs:
  Key With Whitespace: "I am a value with whitespace in it"

Seems as through spring can parse this yaml fine, and it is apparently valid yaml. However, spring (SnakeYaml?) removes the spaces in the Key string:

KeyWithWhitespace -> I am a value with whitespace in it

An easy solution is to designate a special character for space and replace it within the application, but I was wondering if spring already handled this in some fashion? Perhaps there is a way to escape a space in the config in such a way that spring (SnakeYaml?) knows the we want to keep it, or perhaps there is a way to configure this?

For the sake of completeness I've tried using single and double quotations as well as \s \b.

Update:

After some additional research I found an example from SnakeYaml repository that seems to indicate that what I'm looking for should be possible: https://bitbucket.org/asomov/snakeyaml/wiki/Documentation#markdown-header-block-mappings

Specifically this example:

# YAML
base armor class: 0
base damage: [4,4]
plus to-hit: 12
plus to-dam: 16
plus to-ac: 0
# Java
{'plus to-hit': 12, 'base damage': [4, 4], 'base armor class': 0, 'plus to-ac': 0, 'plus to-dam': 16}

In the example the spaces persist in the keys. Unfortunately, I'm at a loss with regard to figuring out where the whitespace is actually getting removed.


Solution

  • For map keys with special characters you need to surround the key with '[]' for the key to be used as specified.

    So, in your case it will be

    whitespace.test.configs:
      '[Key With Whitespace]': "I am a value with whitespace in it"