文章目录
- @EnableConfigurationProperties 开启单个配置属性绑定
- @EnableConfigurationProperties 开启多个配置属性绑定
- @EnableConfigurationProperties 的应用场景
@EnableConfigurationProperties
是 SpringBoot 在
org.springframework.boot.context.properties
包下提供的一个注解,该注解通常被声明于使用
@Configuration
注解标识的类上方,
@EnableConfigurationProperties
的作用是通知一或多个被
@ConfigurationProperties
注解标识的类开启配置绑定功能。
@EnableConfigurationProperties 开启单个配置属性绑定
以下通过一个案例,演示使用 @EnableConfigurationProperties
开启单个配置属性 Bean 的绑定。
首先,在 application.yml
中声明配置:
school:name: 人才大学address: 北京市type: A_Type
然后,定义一个配置属性 Bean 与上述配置进行绑定:
java">import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;@Data
@ConfigurationProperties(prefix = "school")
public class SchoolProperties {private String name;private String address;private String type;}
最后,定义一个配置类并通知配置属性 Bean 开启配置绑定:
java">import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableConfigurationProperties(SchoolProperties.class)
public class CustomConfig {// 其他的配置}
此时在 application.yml
中声明的相关配置,将被成功绑定到 SchoolProperties
中。
@EnableConfigurationProperties 开启多个配置属性绑定
基于上述案例进行拓展,以下是使用 @EnableConfigurationProperties
开启多个配置属性绑定的案例。
首先,新增一组配置声明:
home:ip: 127.0.0.1city: 深圳市
然后,定义一个配置属性 Bean 与上述配置进行绑定:
java">@Data
@ConfigurationProperties(prefix = "home")
public class HomeProperties {private String ip;private String city;}
最后,修改配置类,新增上述配置属性 Bean 的声明:
java">@Configuration
@EnableConfigurationProperties({SchoolProperties.class,HomeProperties.class
})
public class CustomConfig {// 其他的配置}
此时在 application.yml
中声明的相关配置,将被成功绑定到 SchoolProperties
与 HomeProperties
中。
@EnableConfigurationProperties 的应用场景
对于使用 @EnableConfigurationProperties
注解搭配 @ConfigurationProperties
注解进行配置绑定的应用而言,实际上有多种方案都可以做到与其等效的效果。例如:
- 使用
@Component
注解搭配@ConfigurationProperties
注解使用。 - 使用
@Bean
注解搭配@ConfigurationProperties
与@Configuration
注解使用。
相较于上述两种方式,使用 @EnableConfigurationProperties
注解,可以不再需要在配置属性 Bean 的上方再添加 @Component
或者在配置类中通过 @Bean
声明某个配置属性 Bean。
@EnableConfigurationProperties
注解的优点是方便将配置集中在一起进行管理,从而清晰的看到实现统一绑定配置的 Bean,而无需在自定义的 Bean 中逐个查找。例如:
java">import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableConfigurationProperties({SchoolProperties.class,HomeProperties.class
})
public class CustomConfig {// 其他的配置}
上例中,可以十分清晰、明确地观察到 SchoolProperties
与 HomeProperties
在应用程序中进行了配置绑定。