【问题标题】:Spring Boot - Populate List/Collection from Application.properties?Spring Boot - 从 Application.properties 填充列表/集合?
【发布时间】:2016-09-29 21:03:19
【问题描述】:

这可能是一个愚蠢的问题,但是否可以在 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/

我知道我可以分解逗号分隔的字符串,但我只是好奇是否有原生的 spring boot 方法来做到这一点?

【问题讨论】:

  • 你试过了吗?似乎尝试这个比写一个问题花费的时间更少:)
  • 是的,如果可能的话我不知道属性文件中的秘密语法,我的问题只是使用了我认为很明显的东西,我得到....引起:org.springframework.beans .factory.BeanCreationException:无法自动装配字段:私有 java.util.List com.cwssoft.reportout.filter.JwtFilter.excludePatterns;嵌套异常是 java.lang.IllegalArgumentException:无法解析字符串值“${hermes.api.excluded.jwt}”中的占位符“hermes.api.excluded.jwt”
  • 这令人惊讶,我原以为有一种更简洁的方法(与简单的 string.split 相比),因为它在 applicationContext 文件中很常见。谢谢
  • 哦,github.com/spring-projects/spring-boot/issues/… 您不必拆分,现在在启动时显然已默认启用。 + YAML 似乎支持您的语法:docs.spring.io/spring-boot/docs/current/reference/html/…

标签: java spring spring-boot


【解决方案1】:

事实证明它确实有效。但是,您似乎必须使用配置属性,因为简单的@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(...
    ...

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 2016-12-13
    • 2014-12-25
    • 2020-12-28
    • 2019-06-16
    • 2019-06-16
    • 2018-09-15
    • 2020-10-11
    • 2017-08-07
    相关资源
    最近更新 更多