英文:
Cannot bind Map to Object in Spring Configuration Properties from YAML file
问题
我在我的Spring Boot的application.yml文件中有以下配置:
```yaml
project:
country-properties:
france:
capital: 巴黎
population: 60
并且我有一个属性类:CountryProperties:
@Getter
@AllArgsConstructor
@ConstructorBinding
@ConfigurationProperties(prefix="project.country-properties")
public class CountryProperties {
private Map<String, CountryData> countryProperties;
@Getter
@Setter
public static class CountryData {
private String capital;
private Integer population;
}
然而我的CountryProperties总是为null,这是因为与CountryData对象的映射失败了。
对我写的有什么错误有什么想法吗?
<details>
<summary>英文:</summary>
I have the following configuration in my Spring boot's application.yml file:
project:
country-properties:
france:
capital: paris
population: 60
And I have the the properties class : CountryProperties :
```java
@Getter
@AllArgsConstructor
@ConstructorBinding
@ConfigurationProperties(prefix="project.country-properties")
public class CountryProperties {
private Map<String, CountryData> countryProperties;
@Getter
@Setter
public static class CountryData {
private String capital;
private Integer population;
}
However my CountryProperties is always null, and it's because of a failed mapping with the CountryData object.
Any ideas what is wrong with what I wrote?
答案1
得分: 1
以下是翻译好的部分:
你有注解 @ConstructorBinding
。这个注解告诉 Spring 查找你的类中具有与配置属性相对应的参数的构造函数,然后将绑定这些属性。
你缺少的部分是:
this.countryProperties = countryProperties;
}```
更新:
再次检查您的代码后,看起来您没有正确地将配置映射到实例字段。请将 ```@ConfigurationProperties(prefix="project.country-properties")``` 更新为 ```@ConfigurationProperties(prefix="project")```。
还要将 ```@ConstructorBinding``` 替换为 ```@Configuration```。
<details>
<summary>英文:</summary>
You have the annotation ```@ConstructorBinding```. This annotation tells Spring to look for a constructor in your class that has parameters corresponding to your configuration properties, and then will bind the properties.
What you are missing is:
public CountryProperties(Map<String, CountryData> countryProperties) {
this.countryProperties = countryProperties;
}
Update:
After inspecting your code again, it looks like you aren't mapping the configuration correctly to the instance field. Please update your ```@ConfigurationProperties(prefix="project.country-properties")``` to ```@ConfigurationProperties(prefix="project")```.
Also replace the ```@ConstructorBinding``` with ```@Configuration```.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论