简体   繁体   English

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

[英]Spring Boot: read list from yaml using @Value or @ConfigurationProperties

I want to read a list of hosts from a yaml file (application.yml), the file looks like this:我想从 yaml 文件 (application.yml) 中读取主机列表,文件如下所示:

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

(Example 1) (示例 1)

My class used defines the value like this:我使用的类定义了这样的值:

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

But reading fails as Spring complains about this:但是阅读失败,因为 Spring 抱怨这个:

java.lang.IllegalArgumentException: Could not resolve placeholder 'cors.hosts.allow' in string value "${cors.hosts.allow}" java.lang.IllegalArgumentException:无法解析字符串值“${cors.hosts.allow}”中的占位符“cors.hosts.allow”

When I change the file like this the property can be read but naturally it does not contain the list but only one entry:当我像这样更改文件时,可以读取该属性,但自然它不包含列表,而只包含一个条目:

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

(I know that I could read the values as a single line and split them by "," but I do not want to go for a workaround yet) (我知道我可以将这些值作为一行读取并用","将它们分开","但我还不想寻求解决方法)

This does not work either (although I think this should be valid according to snakeyamls docs ):这也不起作用(尽管我认为根据snakeyamls docs这应该是有效的):

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

(Skipping the !!seq and just using the [ / ] is a failure too) (跳过!!seq并仅使用[ / ]也是失败的)

I read the suggestion here which involves using @ConfigurationProperties and transferred the example to Java and used it with the yaml file you see in Example1:我在这里阅读了涉及使用@ConfigurationProperties的建议,并将示例转移到 Java 并将其与您在 Example1 中看到的 yaml 文件一起使用:

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

When I run this I get this complaint:当我运行这个时,我收到了这个投诉:

org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult: 1 errors Field error in object 'cors.hosts' on field 'allow': rejected value [null]; org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult: 1 个错误字段“允许”对象“cors.hosts”中的字段错误:拒绝值[null]; codes [NotNull.cors.hosts.allow,NotNull.allow,NotNull];代码 [NotNull.cors.hosts.allow,NotNull.allow,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [cors.hosts.allow,allow];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [cors.hosts.allow,allow]; argumen ts [];参数 ts []; default message [allow]];默认消息 [允许]];

I searched for other means to have my CORS hosts configurable and found this Spring Boot issue but as this is not yet finished I can't use it as a solution.我搜索了其他方法来配置我的 CORS 主机并发现了这个Spring Boot 问题,但由于尚未完成,我无法将其用作解决方案。 All of this is done with Spring Boot 1.3 RC1所有这些都是通过 Spring Boot 1.3 RC1 完成的

It's easy, the answer is in this doc and also in this one 这很容易,答案是在这个文档 ,并在这一个

So, you have a yaml like this: 所以,你有这样一个yaml:

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

Then you first bind the data 然后首先绑定数据

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
}

Then in another component you just do 然后在另一个组件中你做

@Autowired
private AllowedHosts allowedHosts;

And you are done! 你完成了!

use comma separated values in application.yml 在application.yml中使用逗号分隔值

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

java code for access 用于访问的java代码

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

I tried and succeeded ;) 我尝试过并且成功了;)

I have been able to read list from properties like below way- 我已经能够从以下属性中读取列表 -

Properties- 属性 -

cors.hosts.allow[0]=host-0
cors.hosts.allow[1]=host-1

Read property- 阅读财产 -

@ConfigurationProperties("cors.hosts")
public class ReadProperties {
    private List<String> allow;

    public List<String> getAllow() {
       return allow;
    }
    public void setAllow(List<String> allow) {
        this.allow = allow;
    }
}

I met the same problem, But solved, give you my solution我遇到了同样的问题,但解决了,给你我的解决方案

exclude-url: >
  /management/logout,
  /management/user/login,
  /partner/logout,
  /partner/user/login

success in the version of Spring boot 2.1.6.RELEASE Spring boot 2.1.6.RELEASE版本成功

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM