javaspringspring-properties

Changing delimiter in @ConfigurationProperties for reading a List property


I have a list of values in one property in application.properties file:

my-property=abc,def,ghi

And I load it in my @ConfigurationProperties class:

@Configuration
@ConfigurationProperties
public class MyProperties {

    private List<String> myProperty;
}

But I don't know how to change delimiter (from comma to semicolon or other separator):

my-property=abc;def;ghi

I know I can write workaround, but I don't want to use them because:

@Value("#{'${my-property}'.split(';')}")
private List<String> myProperty;
my-property[0]=abc
my-property[1]=def
my-property[2]=ghi
private String myProperties;

public List<String> getMyProperty() {
    return Arrays.asList(myProperties.split(";"));
}

Solution

  • Basic usage

    The answer is annotation @Delimiter.

    You can set any string as delimiter (default value is ,). For example:

    @Configuration
    @ConfigurationProperties
    public class MyProperties {
    
        @Delimiter(";")
        private List<String> myProperty;
    }
    

    and application.properties file:

    my-property=abc;def;ghi
    

    Longer strings

    Longer string as delimiters also works. For example annotation @Delimiter("---") with property:

    my-property=abc---def---ghi
    

    How it works under the hood

    If you interested, I found this annotation by debugging Spring source code. The key is class DelimitedStringToArrayConverter (check source code to find the annotation). You can see default value , when delimiter is null.

    How it works:

        public void setMyProperty(List<String> myProperty) {
            this.myProperty = myProperty;
        }