如何通过application.yml创建复合POJO并初始化Employee列表Bean
可以通过application.yml配置生成Employee类型的Bean列表
当然可以实现,以下是具体操作步骤:
1. 调整POJO并添加配置注解
首先确保POJO具备Getter/Setter方法(可通过Lombok的@Data注解简化代码),同时创建一个容器类来包裹List<Employee>,并给容器类添加@ConfigurationProperties注解指定配置前缀:
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; @Data @ConfigurationProperties(prefix = "employees") public class EmployeeList { private List<Employee> items; @Data public static class Employee { private String name; private String department; private Address address; } @Data public static class Address { private String street; private String houseNo; private String postCode; } }
注:如果你的
Employee和Address是独立类,只需给每个类单独添加@Data注解,容器类保持上述结构即可。
2. 在application.yml中配置员工列表
按照前缀和层级结构编写配置,对应POJO的字段名:
employees: items: - name: "张三" department: "技术部" address: street: "科技路" houseNo: "123号" postCode: "100000" - name: "李四" department: "人事部" address: street: "民生路" houseNo: "456号" postCode: "200000"
3. 启用配置属性扫描
在Spring Boot启动类上添加@ConfigurationPropertiesScan注解,让Spring自动扫描并生成EmployeeList类型的Bean:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @SpringBootApplication @ConfigurationPropertiesScan public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
4. 注入并使用Bean
之后就可以在任意Spring组件中注入EmployeeList,获取配置好的员工列表:
import org.springframework.stereotype.Service; import java.util.List; @Service public class EmployeeService { private final List<Employee> employeeList; // 构造方法注入 public EmployeeService(EmployeeList employeeList) { this.employeeList = employeeList.getItems(); } public void printEmployees() { employeeList.forEach(emp -> { System.out.println("姓名:" + emp.getName() + ",部门:" + emp.getDepartment()); }); } }
关键注意点
- 必须保证POJO有Getter/Setter方法,Spring依赖这些方法完成属性绑定。
- 不能直接用
@ConfigurationProperties绑定顶级集合(比如直接List<Employee>),必须通过容器类包裹。 - YAML中的属性名支持驼峰与短横线的自动映射,比如POJO中的
houseNo可以对应YAML中的house-no或houseNo。
内容的提问来源于stack exchange,提问作者BobCoder
相关产品推荐
相关产品推荐

