Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring启动:无法从yaml读取对象列表_Spring_Yaml - Fatal编程技术网

Spring启动:无法从yaml读取对象列表

Spring启动:无法从yaml读取对象列表,spring,yaml,Spring,Yaml,我有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 cl

我有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设置正确,但端点列表为空。不能得到为什么

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

您有两个简单的选项:

默认情况下使用application.yml和Spring引导加载,您可以使用application-xxx.yml并设置@ActiveProfilesvalue=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;
}