初探-@EnableConfigurationProperties这个注释

发布时间 2023-08-03 10:19:08作者: wrhiuo

@EnableConfigurationProperties 是 Spring Boot 中的一个注解,用于启用配置属性绑定。

在 Spring Boot 应用中,我们可以通过 @ConfigurationProperties 注解来将配置文件中的属性绑定到 JavaBean 中。但是,默认情况下,这些属性绑定需要手动将对应的 JavaBean 注册为 Spring 的 Bean。使用 @EnableConfigurationProperties 注解可以简化这个过程,它会自动将带有 @ConfigurationProperties 注解的类注册为 Spring 的 Bean。

具体使用方法如下:

  1. 在一个带有 @Configuration 注解的配置类上添加 @EnableConfigurationProperties 注解,并将需要绑定属性的类作为参数传递给注解。例如:
@Configuration
@EnableConfigurationProperties(MyProperties.class)
public class MyConfig {
}
  1. MyProperties 类上添加 @ConfigurationProperties 注解,指定配置属性的前缀。例如:
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
    // 定义需要绑定的属性和对应的字段
    private String name;
    private int age;
    // ...
}
  1. application.properties(或 application.yml)配置文件中定义需要绑定的属性。例如:
my.name=John
my.age=30

通过以上配置,MyProperties 类中的 nameage 字段将自动绑定到 application.properties 中的对应属性,并在 MyConfig 类中作为一个 Spring 的 Bean 注册,可以在其他组件中直接注入使用。

使用 @EnableConfigurationProperties 注解可以方便地启用属性绑定功能,减少了手动注册 Bean 的步骤,使配置属性的使用更加简单和便捷。