springboot @ConfigurationProperties 读不到yml含List
时间: 2023-11-21 17:57:39 浏览: 118
当使用@ConfigurationProperties读取yml文件时,如果yml文件中包含List,需要注意以下几点:
1. 确保yml文件中List的格式正确,例如:
```yaml
my:
list:
- item1
- item2
```
2. 确保在@ConfigurationProperties类中定义List时,使用List类型,并且提供getter和setter方法,例如:
```java
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private List<String> list;
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
```
3. 确保在启动类中使用@EnableConfigurationProperties注解启用@ConfigurationProperties,例如:
```java
@SpringBootApplication
@EnableConfigurationProperties(MyProperties.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
如果以上三点都满足,但仍然读取不到yml文件中的List,可以尝试在@ConfigurationProperties注解中添加@ConstructorBinding注解,例如:
```java
@ConfigurationProperties(prefix = "my")
@ConstructorBinding
public class MyProperties {
private List<String> list;
public MyProperties(List<String> list) {
this.list = list;
}
public List<String> getList() {
return list;
}
}
```
阅读全文