Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Populate List/Collection from Application.properties?

This may be a stupid questions, but is it possible to populate a list form an application.properties file in Spring Boot. Here is a simple example:

public class SomeClass {
    @Value("${hermes.api.excluded.jwt}")
    private List<String> excludePatterns = new ArrayList<>();
    // getters/settings ....
}

application.properties

// Is something along these lines possible????
hermes.api.excluded.jwt[0]=/api/auth/
hermes.api.excluded.jwt[1]=/api/ss/

I know I could explode a comma separated string, but I was just curious if there is a native spring boot way to do this?

like image 366
csyperski Avatar asked Dec 19 '22 16:12

csyperski


1 Answers

Turns out it does work. However, it seems you have to use configuration properties, since simple @Value("${prop}") seems to use a different path under the hood. (There are some hints to DataBinder in this secion. Not sure if related.)

application.properties

foo.bar[0]="a"
foo.bar[1]="b"
foo.bar[2]="c"
foo.bar[3]="d"

and in code

@Component
@ConfigurationProperties(prefix="foo")
public static class Config {
    private final List<String> bar = new ArrayList<String>();
    public List<String> getBar() {
        return bar;
    }
}

@Component
public static class Test1 {
    @Autowired public Test1(Config config) {
        System.out.println("######## @ConfigProps " + config.bar);
    }
}

results in

######## @ConfigProps ["a", "b", "c", "d"]

While

@Component
public static class Test2 {
    @Autowired public Test2(@Value("${foo.bar}") List<String> bar) {
        System.out.println("######## @Value " + bar);
    }
}

results in

java.lang.IllegalArgumentException: Could not resolve placeholder 'foo.bar' in string value "${foo.bar}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(...
    ...
like image 90
zapl Avatar answered May 19 '23 02:05

zapl