问题描述
这可能是一个愚蠢的问题,但是可以在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})
似乎在引擎盖下使用了不同的路径。 (在。不确定是否相关。)
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填充列表/集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!