无法在Spring配置属性中将Map绑定到来自YAML文件的Object

huangapple go评论57阅读模式
英文:

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&#39;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=&quot;project.country-properties&quot;) 
public class CountryProperties {
      private Map&lt;String, CountryData&gt; 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=&quot;project.country-properties&quot;)``` 更新为 ```@ConfigurationProperties(prefix=&quot;project&quot;)```。

还要将 ```@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&#39;t mapping the configuration correctly to the instance field. Please update your ```@ConfigurationProperties(prefix=&quot;project.country-properties&quot;)``` to ```@ConfigurationProperties(prefix=&quot;project&quot;)```.

Also replace the ```@ConstructorBinding``` with ```@Configuration```.

</details>



huangapple
  • 本文由 发表于 2023年2月19日 18:50:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定