Spring启动:无法从yaml读取对象列表
我有custom.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
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;
}