Spring Boot - 从Application.properties填充列表/集合?

时间:2016-05-31 18:02:13

标签: java spring spring-boot

这可能是一个愚蠢的问题,但是可以在Spring Boot中填充application.properties文件中的列表。这是一个简单的例子:

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/

我知道我可以爆炸一个逗号分隔的字符串,但我只是好奇是否有一个原生的春季启动方式来做这个?

1 个答案:

答案 0 :(得分:10)

原来它确实有效。但是,您似乎必须使用配置属性,因为简单的@Value("${prop}")似乎使用了不同的路径。 (this secion中有DataBinder的一些提示。不确定是否相关。)

application.properties

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

并在代码中

@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);
    }
}

结果

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

虽然

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

结果

java.lang.IllegalArgumentException: Could not resolve placeholder 'foo.bar' in string value "${foo.bar}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(...
    ...