user13016811
user13016811

Reputation:

Preserve leading space in application yaml properties

I've got a list of properties in yml file

foo:
    bar:  One., Two., Three

when converting them to list

@Value("\${foo.bar}")
public var listOfBar: List<String> = mutableListOf()

Leading spaces are trimmed so I get "One." "Two." "Three.", but what I need is " One." " Two." " Three." with spaces before each. Putting '\u0020' in front didn't helped, it got trimmed anyway.

Upvotes: 1

Views: 2398

Answers (4)

Abhi
Abhi

Reputation: 94

Removing spaces like this will break the purpose of trim() for yaml file. Though I don't understand the use-case in which you may require this. but, I can suggest to use a custom pattern to achieve this as follows:

You can have tokens for spaces required in yaml file:

foo:
  bar:  $__$One., Two., Three$_$

Have a different class just to retrieve the configs:

public class Configs {
    @Value("${foo.bar}")
    private List<String> yourList;
    
    public List<String> getYourList() {
        // before returning, replace $_$ with space in yourList
    }
}

Use it in your code

class UseHere {
    
    @Autowired
    private Configs configs;
    
    ...
    
    // read as follows
    configs.getYourList().get(0);
    ...
    
}

Upvotes: 0

user13016811
user13016811

Reputation:

I ended up doing this. And it's worked

 @Value("#{'\${foo.bar}'.split(',')}")
 public var listOfBar: List<String> = mutableListOf()

and surrounded properties with "

foo:
    bar:  " One., Two., Three"

Upvotes: 1

Costi Ciudatu
Costi Ciudatu

Reputation: 38205

When you expect List<String> or String[], Spring will split the input string value using , as separator.

To produce the string you want, you need to have the whitespace within quotes (otherwise it is ignored as per the yaml syntax):

foo:
    bar: " One., Two., Three"

However, the Spring default converter may call trim() on every token (I don't remember exactly if this is actually the case) simply dropping all your leadin/trailing spaces anyway.

In this case, you may want to register a different converter that doesn't trim or -- far better -- just take the string and split it yourself.

Upvotes: 2

Lino
Lino

Reputation: 19926

Simply use " around your values:

foo:
    bar: " One."," Two."," Three"

Also you can use the explicit list format:

foo:
    bar: 
        - " One."
        - " Two."
        - " Three"

Upvotes: 3

Related Questions