Spring Boot YAML复杂数组配置如何类型安全绑定到Java List
解决方法
核心原因
@Value注解仅支持注入简单类型、单个配置项,不支持直接绑定嵌套的集合类结构到自定义POJO列表,这类结构化配置的绑定需要使用Spring Boot提供的@ConfigurationProperties能力实现。
具体实现步骤
1. 定义自定义POJO类
首先定义ChangedName类,必须包含无参构造、对应属性的getter和setter方法,Spring会自动将yaml中的kebab-case命名和POJO的驼峰命名做映射:
public class ChangedName { private String originalName; private String changedName; // 无参构造是必须项 public ChangedName() {} // Getter & Setter public String getOriginalName() { return originalName; } public void setOriginalName(String originalName) { this.originalName = originalName; } public String getChangedName() { return changedName; } public void setChangedName(String changedName) { this.changedName = changedName; } }
如果项目使用Lombok,直接加@Data注解即可省去手写构造、getter、setter的代码。
2. 定义配置绑定类
创建专门的配置属性类,添加@ConfigurationProperties注解指定配置前缀:
import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; @ConfigurationProperties(prefix = "") public class NameChangeProperties { // 属性名要和yaml中的根配置名name-change对应(自动转驼峰为nameChange) private List<ChangedName> nameChange; public List<ChangedName> getNameChange() { return nameChange; } public void setNameChange(List<ChangedName> nameChange) { this.nameChange = nameChange; } }
3. 开启配置属性扫描
在Spring Boot启动类上添加@EnableConfigurationProperties注解,注册配置绑定类:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @EnableConfigurationProperties(NameChangeProperties.class) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
4. 注入使用
在需要使用的RestController中直接注入配置类即可获取对应的List集合:
import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { private final NameChangeProperties properties; // 构造注入 public TestController(NameChangeProperties properties) { this.properties = properties; } public void test() { // 直接获取绑定完成的List<ChangedName> List<ChangedName> nameList = properties.getNameChange(); } }
简化写法(无需单独配置类)
如果不想单独写配置绑定类,也可以直接把@ConfigurationProperties加在Controller上,直接绑定属性到Controller内部:
@RestController @ConfigurationProperties(prefix = "") public class TestController { private List<ChangedName> nameChange; // 必须添加nameChange的getter和setter public List<ChangedName> getNameChange() { return nameChange; } public void setNameChange(List<ChangedName> nameChange) { this.nameChange = nameChange; } }
内容的提问来源于stack exchange,提问作者Rohan Perera
相关产品推荐
相关产品推荐

