春季启动:无法从 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 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列表为空。不明白为什么?

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

您有 2 个简单的选项:

使用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;
}

最新更新