@ConfigurationProperties 两种用法:选对就完事儿

问题

配置文件这么写:

1
2
3
4
property:
param:
high: 180
weigth: 70

怎么优雅地映射到 Java 对象?

方式一:@Component —— 毛遂自荐

1
2
3
4
5
6
7

@Component
@ConfigurationProperties(prefix = "property.param")
public class PropertyEntity {
private Integer high;
private Integer weigth;
}

一句话:自己跳进 Spring 容器,简单但耦合。

特点:依赖组件扫描、配置类耦合 Spring、隐式注册。

方式二:@EnableConfigurationProperties —— 伯乐相马

1
2
3
4
5
6
7
8
9
10
11
12
// 配置类保持纯净
@ConfigurationProperties(prefix = "property.param")
public class PropertyEntity {
private Integer high;
private Integer weigth;
}

// 配置类里显式声明
@Configuration
@EnableConfigurationProperties(PropertyEntity.class)
public class MyConfig {
}

一句话:显式注册,解耦且清晰。

特点:不依赖扫描、配置类是纯 POJO、显式注册(推荐)。

怎么选?

Demo 或小项目用方式一,正经项目用方式二。

核心差异

方式一依赖组件扫描,配置类和 Spring 强耦合,注册过程隐式不清晰。

方式二不依赖扫描机制,配置类保持纯 POJO,显式声明依赖关系更专业。


一句话总结:能说明白的别让框架猜,方式二更专业。


使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13

@RestController
public class TestController {

@Autowired
private PropertyEntity propertyEntity;

@GetMapping("/config")
public String getConfig() {
return "身高: " + propertyEntity.getHigh() +
", 体重: " + propertyEntity.getWeigth();
}
}