Spring Boot:使用 @Value 或 @ConfigurationProperties 从 yaml 读取列表

新手上路,请多包涵

我想从 yaml 文件(application.yml)中读取主机列表,该文件如下所示:

 cors:
    hosts:
        allow:
            - http://foo1/
            - http://foo2/
            - http://foo3/

(例 1)

我使用的类定义了这样的值:

 @Value("${cors.hosts.allow}")
List<String> allowedHosts;

但是阅读失败,因为 Spring 抱怨这一点:

java.lang.IllegalArgumentException:无法解析字符串值“${cors.hosts.allow}”中的占位符“cors.hosts.allow”

当我像这样更改文件时,可以读取属性,但自然它不包含列表,而只包含一个条目:

 cors:
    hosts:
        allow: http://foo1, http://foo2, http://foo3

(我知道我可以将这些值读取为一行并将它们拆分为 "," 但我还不想寻求解决方法)

这也不起作用(尽管我认为根据 snakeyamls docs 这应该是有效的):

 cors:
    hosts:
        allow: !!seq [ "http://foo1", "http://foo2" ]

(跳过 !!seq 而只使用 [ / ] 也是失败的)

我在 这里 阅读了涉及使用 @ConfigurationProperties 的建议并将示例传输到 Java 并将其与您在示例 1 中看到的 yaml 文件一起使用:

 @Configuration
@EnableWebMvc
@ConfigurationProperties(prefix = "cors.hosts")
public class CorsConfiguration extends WebMvcConfigurerAdapter {
    @NotNull
    public List<String> allow;
...

当我运行它时,我收到了以下投诉:

org.springframework.validation.BindException:org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult:1 个错误字段“允许”上的对象“cors.hosts”中的字段错误:拒绝值 [null];代码 [NotNull.cors.hosts.allow,NotNull.allow,NotNull];参数 [org.springframework.context.support.DefaultMessageSourceResolvable:代码 [cors.hosts.allow,allow];参数 ts [];默认消息[允许]];

我搜索了其他方法来让我的 CORS 主机可配置,并发现了这个 Spring Boot 问题,但由于这还没有完成,我不能将它用作解决方案。所有这些都是通过 Spring Boot 1.3 RC1 完成的

原文由 Marged 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

在 application.yml 中使用逗号分隔值

corsHostsAllow: http://foo1/, http://foo2/, http://foo3/

用于访问的java代码

@Value("${corsHostsAllow}")
String[] corsHostsAllow

我尝试并成功了;)

原文由 Ahmet Vehbi Olgaç 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题