Spring Boot - 从Application.properties填充列表/集合? [英] Spring Boot - Populate List/Collection from Application.properties?

查看:1417
本文介绍了Spring Boot - 从Application.properties填充列表/集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是可以在Spring Boot中填充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

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?

推荐答案

原来它确实有效。但是,似乎你必须使用配置属性,因为简单的 @Value($ {prop})似乎在引擎盖下使用了不同的路径。 (在 DataBinder 的一些提示features-external-config.html #boot-features-external-config-loading-yamlrel =noreferrer> this secion 。不确定是否相关。)

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"

和代码

@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(...
    ...

这篇关于Spring Boot - 从Application.properties填充列表/集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆