java 通过配置属性实现Spring Bean自自动装配

xdnvmnnf  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(133)

我尝试使用@ConfigurationProperties从YAML文件直接填充配置对象。但是当我检查人的对象时,名字和年龄被填充,但是孩子是空的。我使用的是spring Boot 2.7.4版本。spring不支持这一点,或者其他处理这种情况的方法不支持吗?

@ConfigurationProperties("config")
@Component
public class PersonConfiguration {

    private Person person;

    //setter getters
}

public class Person {
    private String name;
    private int age;
    @NestedConfigurationProperty
    private Person child;

//setter getters of all 3 
}

config:
  person:
    name: "my name"
    age: 40
    child:
      name: "child1"
      age: 14
mmvthczy

mmvthczy1#

配置文件中的子定义似乎不表示Person类结构,它缺少子属性。请尝试以下操作:配置:人员:姓名:“我的姓名”年龄:40岁孩子:姓名:“儿童1”年龄:14子项:空

7kjnsjlb

7kjnsjlb2#

您应该不需要PersonConfiguration
这将工作:

@Configuration
@ConfigurationProperties("config.person")
public class Person {
    private String name;
    private int age;
    private Person child;
   
    //setter and getters
}

相关问题