首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring boot:无法从yaml读取对象列表

Spring boot:无法从yaml读取对象列表
EN

Stack Overflow用户
提问于 2019-12-02 04:02:20
回答 1查看 96关注 0票数 0

我有包含以下内容的custom.yaml文件:

代码语言:javascript
复制
refill-interval-millis: 1000

endpoints:
  - path: /account/all
    rate-limit: 10
  - path: /account/create
    rate-limit: 20

和我的类来读取该文件:

代码语言:javascript
复制
@Component
@PropertySource("classpath:custom.yaml")
@ConfigurationProperties
public class Properties {

    private int refillIntervalMillis;
    private List<Endpoint> endpoints = new ArrayList<>();

    // getters/setters

    public static class Endpoint {
        private String path;
        private int rateLimit;

        // getters/setters
    }
}

因此,当我运行代码时,refillIntervalMillis设置正确,但endpoints列表为空。得不到为什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-02 18:55:11

你不能直接对YAML文件使用@PropertySource:YAML Shortcomings

你有两个简单的选择:

默认情况下使用application.yml和Spring Boot loads (您可以使用application-xxx.yml和设置@ActiveProfiles(value = "xxx")

手动加载YAML文件:

代码语言:javascript
复制
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    var propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    var yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
    yamlPropertiesFactoryBean.setResources(new ClassPathResource("custom.yaml"));
    propertySourcesPlaceholderConfigurer.setProperties(yamlPropertiesFactoryBean.getObject());
    return propertySourcesPlaceholderConfigurer;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59129461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档