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

41 浏览
0 Comments

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

我想要从一个yaml文件(application.yml)中读取一组主机列表,文件的内容如下:

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

(示例1)

我定义的类使用以下方式来定义这个值:

@Value("${cors.hosts.allow}")   
List 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

(我知道我可以将值作为一行读取,然后使用\",\"将它们拆分,但我不想使用这种方法)

这种方式也不起作用(尽管根据snakeyaml文档,我认为这是有效的):

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

(跳过!!seq,仅使用[/]也是无效的)

我在这里看到了建议here,它涉及使用@ConfigurationProperties,我将示例转换为Java,并将其与您在Example1中看到的yaml文件一起使用:

@Configuration
@EnableWebMvc
@ConfigurationProperties(prefix = "cors.hosts")
public class CorsConfiguration extends WebMvcConfigurerAdapter {
    @NotNull
    public List 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 问题,但由于它还没有完成,我不能将其用作解决方案。

所有这些都是使用 Spring Boot 1.3 RC1 完成的。

admin 更改状态以发布 2023年5月19日
0
0 Comments

这很简单,答案在这个文档和这个文档中都有提到。

所以,你有这样一个yaml文件:

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

然后你先绑定数据

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 HostNames; //You can also bind more type-safe objects
}

然后在另一个组件中,你只需要这样:

@Autowired
private AllowedHosts allowedHosts;

就可以了!

0
0 Comments

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

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

用于访问的Java代码

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

我尝试了并成功了 😉

0