【问题标题】:Spring boot: can not read object list from yamlSpring Boot:无法从 yaml 读取对象列表
【发布时间】:2019-12-01 20:02:20
【问题描述】:

我有 custom.yaml 文件的内容:

refill-interval-millis: 1000

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

和我的班级阅读该文件:

@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 列表为空。拿不到为什么?

【问题讨论】:

    标签: spring yaml


    【解决方案1】:

    您不能将@PropertySource 直接用于 YAML 文件:YAML Shortcomings

    你有两个简单的选择:

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

    手动加载 YAML 文件:

    @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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 2016-07-13
      相关资源
      最近更新 更多