跳至主要內容

EnableAutoConfiguration的意义

Mr.Hope...大约 2 分钟

@EnableConfigurationProperties 和 @Component的作用是否有点重复?

@EnableConfigurationProperties@Component 是 Spring Framework 中的两个注解,它们都用于控制对象的创建,但它们的用途和工作方式有所不同。

@Component

@Component 是一个通用的构造型注解,它告诉 Spring 在启动时创建一个 bean 并把它添加到 Spring ApplicationContext 中。Spring 通过扫描类路径下的类来查找 @Component 注解,然后创建这些类的实例并管理它们的生命周期。这些类实例可用于注入到其他 bean 中。

@Component
public class MyComponent {
    // ...
}

@EnableConfigurationProperties

@EnableConfigurationProperties 是 Spring Boot 提供的一个特殊注解,用于启用 @ConfigurationProperties 注解的支持。@ConfigurationProperties 允许你将配置文件中的属性映射到一个带有 getter 和 setter 的 POJO(Plain Old Java Object)上。这个 POJO 需要有一个无参数的构造函数,它的字段名与配置文件中的属性名相对应。

@ConfigurationProperties(prefix = "my")
public class MyProperties {
    private String property;
    // getter and setter ...
}

然后,你需要在一个配置类上使用 @EnableConfigurationProperties 来启用这个属性类。

@Configuration
@EnableConfigurationProperties(MyProperties.class)
public class MyConfiguration {
    // ...
}

为什么不直接使用 @Component 呢?

你可以直接将 @Component@ConfigurationProperties 注解用在同一个类上。这将会让 Spring Boot 创建一个 bean,并将 application.propertiesapplication.yml 中以 “my” 为前缀的属性注入到这个 bean 中。

@ConfigurationProperties(prefix = "my")
@Component
public class MyProperties {
  private String property;
  // getter and setter ...
}

这是一个可行的方法,但这种方式的灵活性较差。当你的应用程序变得越来越大,配置属性类也会越来越多,如果每个类都使用 @Component,那么这些配置属性类将会分散在你的整个代码库中。这将使得管理和查找这些配置属性类变得困难。

另一方面,使用 @EnableConfigurationProperties 允许你在一个地方集中管理所有的配置属性类。你可以在一个配置类中使用 @EnableConfigurationProperties,并将所有的配置属性类作为参数传入。这样做可以使得代码更加清晰,管理和查找配置属性更方便。

@Configuration
@EnableConfigurationProperties({MyProperties.class, OtherProperties.class, ...})
public class MyConfiguration {
    // ...
}

本质意义:第三方jar包