找回密码
 立即注册
首页 业界区 安全 @ConfigurationProperties的三种正确使用方式

@ConfigurationProperties的三种正确使用方式

慎气 3 天前
三种正确使用 @ConfigurationProperties 的方式:

1. 使用 @EnableConfigurationProperties 注册

在某个配置类(通常是主启动类或 @Configuration 类)上添加 @EnableConfigurationProperties(YourPropertiesClass.class):
  1. @SpringBootApplication
  2. @EnableConfigurationProperties(MyProperties.class)
  3. public class MyApp {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(MyApp.class, args);
  6.     }
  7. }
复制代码
对应的属性类:
  1. @ConfigurationProperties(prefix = "my")
  2. public class MyProperties {
  3.     private String name;
  4.     // getter/setter
  5. }
复制代码
注意:此时 MyProperties 不需要加 @Component。
2. 将属性类本身标记为 Spring 组件(如 @Component)
  1. @Component@ConfigurationProperties(prefix = "my")
  2. public class MyProperties {
  3.     private String name;
  4.     // getter/setter
  5. }
复制代码
这样 Spring 在组件扫描时会自动注册它。
3. 使用 @ConfigurationPropertiesScan 自动扫描

在主类或配置类上添加 @ConfigurationPropertiesScan(Spring Boot 2.2+ 支持):
  1. @SpringBootApplication
  2. @ConfigurationPropertiesScan // 默认扫描当前包及子包
  3. public class MyApp {
  4.     // ...
  5. }
复制代码
然后你的属性类只需:
  1. @ConfigurationProperties(prefix = "my")
  2. public class MyProperties {
  3.     private String name;
  4.     // getter/setter
  5. }
复制代码
注意:此时 MyProperties 不能加 @Component,但必须位于被 @ConfigurationPropertiesScan 扫描到的包路径下。
常见错误原因


  • 你写了 @ConfigurationProperties 类,但没有用以上任一方式注册
  • 用了 @ConfigurationPropertiesScan,但属性类不在扫描路径下。
  • 同时加了 @Component 和 @EnableConfigurationProperties,虽然可能能工作,但属于冗余甚至可能冲突(不推荐)。
推荐做法(Spring Boot 2.2+)

使用 @ConfigurationPropertiesScan + 纯 @ConfigurationProperties 类(不加 @Component),更清晰、解耦。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册