Spring 启动 : read list from yaml using @Value or @ConfigurationProperties

标签 spring configuration spring-boot yaml snakeyaml

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

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

(示例 1)

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

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

但由于 Spring 提示,读取失败:

java.lang.IllegalArgumentException: Could not resolve placeholder 'cors.hosts.allow' in string value "${cors.hosts.allow}"

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

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

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

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

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

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

我阅读了建议 here这涉及使用 @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 errors Field error in object 'cors.hosts' on field 'allow': rejected value [null]; codes [NotNull.cors.hosts.allow,NotNull.allow,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [cors.hosts.allow,allow]; argumen ts []; default message [allow]];

我搜索了其他方式让我的 CORS 主机可配置,并找到了 Spring Boot issue但由于这还没有完成,我不能用它作为解决方案。 所有这些都是通过 Spring Boot 1.3 RC1 完成的

最佳答案

很简单,答案就在这个doc以及 this one

所以,你有一个这样的 yaml:

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

那你先绑定(bind)数据

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConfigurationProperties(prefix="cors.hosts")
public class AllowedHosts {
    private List<String> HostNames; //You can also bind more type-safe objects
}

然后在另一个组件中你只是这样做

@Autowired
private AllowedHosts allowedHosts;

你就完成了!

关于 Spring 启动 : read list from yaml using @Value or @ConfigurationProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369878/

相关文章:

perl - 使Perl应用程序可移植。构建一个shell脚本或使用Puppet

java - 独立的 Spring Boot 集成 Java 项目

java - 使用 Spring boot 配置 Jersey

java - Spring Boot YML 中的正则表达式

java - Spring MVC 3.2 Jackson 错误请求

hibernate - 如何在带有注释的 hibernate 中以编程方式验证数据库模式?

java - Spring Boot : Spring always assigns default value to property despite of it being present in . 属性文件

java - spring-oxm:我可以解码文件的子元素吗?

java log4j.xml 多个附加程序共享一个布局

c# - Log4net 对待异常的方式不同于其他日志消息