跳到主要内容
版本:Next

配置绑定(@ConfigurationProperties)

当自定义配置项较多时,逐个 @Value 注入既繁琐又容易出错。@ConfigurationProperties 可以把一组配置类型安全地绑定到一个 Java 对象上,是官方推荐方式。

定义配置​

# application.yml
app:
name: demo
version: 2.0.0
security:
token-expire: 7200
ignore-urls:
- /login
- /captcha

定义属性类​

package com.example.demo.config;

import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {

private String name;
private String version;
private Security security = new Security();

public static class Security {
private long tokenExpire;
private List<String> ignoreUrls;
// getter / setter 省略
}

// getter / setter 省略
}

字段名与 yml 自动映射(token-expire ↔ tokenExpire,支持驼峰转换),集合类型也能直接绑定。

使用​

@RestController
public class InfoController {

private final AppProperties appProperties;

public InfoController(AppProperties appProperties) { // 构造器注入
this.appProperties = appProperties;
}

@GetMapping("/info")
public String info() {
return appProperties.getName() + " v" + appProperties.getVersion();
}
}

两种注册方式​

方式写法适用场景
属性类加 @Component见上例自己项目中的配置类
启动类加 @EnableConfigurationProperties(AppProperties.class)属性类不加注解绑定第三方/不可修改的类

与 @Value 对比​

对比项@Value@ConfigurationProperties
注入粒度单个字段批量绑定整个前缀
松散绑定(驼峰/中划线)不支持支持
复杂类型(List/Map/嵌套对象)支持差原生支持
校验(@Validated)不支持支持 JSR-303 校验
推荐场景个别零散配置一组相关配置

加配置校验​

@Component
@Validated
@ConfigurationProperties(prefix = "app")
public class AppProperties {

@NotBlank
private String name;
// ...
}

启动时如果 app.name 为空,应用直接启动失败并提示,避免问题带病上线。