@ConfigurationProperties 用于将配置文件属性批量绑定到 Java 对象,需指定 prefix、添加 @Component 或 @EnableConfigurationProperties 注册为 Bean,支持嵌套属性与校验,字段名需匹配配置键风格且具备 setter。

在 Spring 中,@ConfigurationProperties 是将配置文件(如 application.yml 或 application.properties)中的属性批量绑定到 Java 对象的便捷方式。它比 @Value 更适合管理结构化、嵌套的配置项。
启用 @ConfigurationProperties 支持
Spring Boot 2.2+ 默认开启配置属性绑定,但需确保项目中已引入 spring-boot-configuration-processor(编译期支持元数据生成,非运行必需,但推荐添加):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
定义配置类并绑定属性
创建一个普通 Java 类,用 @ConfigurationProperties 标注,并指定前缀(如 app.db),再通过 @Component 或 @EnableConfigurationProperties 注入容器:
- 推荐使用
@Component方式(简洁,自动注册为 Bean) - 属性名需与配置文件中 key 的驼峰/中划线风格保持一致(Spring 自动映射,如
max-connections→maxConnections) - 建议添加
@Validated和字段级校验注解(如@NotBlank、@Min(1)),启用校验需配合@Valid在类上
示例:
立即学习“Java免费学习笔记(深入)”;
@Component
@ConfigurationProperties(prefix = "app.db")
@Validated
public class DatabaseProperties {
@NotBlank
private String url;
@NotBlank
private String username;
private int maxConnections = 10;
private Timeout timeout = new Timeout();
// 内部类也支持绑定(需静态或有无参构造)
public static class Timeout {
@Min(100)
private long read = 5000;
private long connect = 3000;
// getter / setter 省略
}
// getter / setter 省略
}
在配置文件中写入对应属性
支持 .properties 和 .yml,注意层级缩进和命名规范:
application.yml 示例:
app:
db:
url: jdbc:mysql://localhost:3306/mydb
username: root
max-connections: 20
timeout:
read: 8000
connect: 4000
application.properties 示例:
app.db.url=jdbc:mysql://localhost:3306/mydb app.db.username=root app.db.max-connections=20 app.db.timeout.read=8000 app.db.timeout.connect=4000
注入并使用配置类
像普通 Bean 一样注入即可,Spring 已完成属性填充和校验(若校验失败,应用启动时抛出 BindException):
@Service
public class DbService {
private final DatabaseProperties dbProps;
public DbService(DatabaseProperties dbProps) {
this.dbProps = dbProps;
}
public void printConfig() {
System.out.println("URL: " + dbProps.getUrl());
System.out.println("Max connections: " + dbProps.getMaxConnections());
System.out.println("Read timeout: " + dbProps.getTimeout().getRead());
}
}
不复杂但容易忽略:确保配置前缀拼写一致、字段可写(有 setter)、类型兼容(如字符串能转为 int),以及配置类被 Spring 扫描到(加 @Component 或显式注册)。


















