@ConfigurationProperties的三种正确使用方式
三种正确使用 @ConfigurationProperties 的方式:
1. 使用 @EnableConfigurationProperties 注册
在某个配置类(通常是主启动类或 @Configuration 类)上添加 @EnableConfigurationProperties(YourPropertiesClass.class):
@SpringBootApplication
@EnableConfigurationProperties(MyProperties.class)
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
对应的属性类:
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String name;
// getter/setter
}
注意:此时
MyProperties不需要加@Component。
2. 将属性类本身标记为 Spring 组件(如 @Component)
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String name;
// getter/setter
}
这样 Spring 在组件扫描时会自动注册它。
3. 使用 @ConfigurationPropertiesScan 自动扫描
在主类或配置类上添加 @ConfigurationPropertiesScan(Spring Boot 2.2+ 支持):
@SpringBootApplication
@ConfigurationPropertiesScan // 默认扫描当前包及子包
public class MyApp {
// ...
}
然后你的属性类只需:
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private String name;
// getter/setter
}
注意:此时
MyProperties不能加@Component,但必须位于被@ConfigurationPropertiesScan扫描到的包路径下。
常见错误原因
- 你写了
@ConfigurationProperties类,但没有用以上任一方式注册。 - 用了
@ConfigurationPropertiesScan,但属性类不在扫描路径下。 - 同时加了
@Component和@EnableConfigurationProperties,虽然可能能工作,但属于冗余甚至可能冲突(不推荐)。
推荐做法(Spring Boot 2.2+)
使用 @ConfigurationPropertiesScan + 纯 @ConfigurationProperties 类(不加 @Component),更清晰、解耦。

浙公网安备 33010602011771号