SpringBoot 开启配置绑定:@EnableConfigurationProperties


@EnableConfigurationProperties 是 SpringBoot 在 org.springframework.boot.context.properties 包下提供的一个注解,该注解通常被声明于使用 @Configuration 注解标识的类上方, @EnableConfigurationProperties 的作用是通知一或多个被 @ConfigurationProperties 注解标识的类开启配置绑定功能。

@EnableConfigurationProperties 开启单个配置属性绑定

以下通过一个案例,演示使用 @EnableConfigurationProperties 开启单个配置属性 Bean 的绑定。

首先,在 application.yml 中声明配置:

school:
  name: 人才大学
  address: 北京市
  type: A_Type

然后,定义一个配置属性 Bean 与上述配置进行绑定:

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 开启配置绑定:

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.1
  city: 深圳市

然后,定义一个配置属性 Bean 与上述配置进行绑定:

@Data
@ConfigurationProperties(prefix = "home")
public class HomeProperties {

    private String ip;

    private String city;

}

最后,修改配置类,新增上述配置属性 Bean 的声明:

@Configuration
@EnableConfigurationProperties({
        SchoolProperties.class,
        HomeProperties.class
})
public class CustomConfig {

    // 其他的配置

}

此时在 application.yml 中声明的相关配置,将被成功绑定到 SchoolPropertiesHomeProperties 中。

@EnableConfigurationProperties 的应用场景

对于使用 @EnableConfigurationProperties 注解搭配 @ConfigurationProperties 注解进行配置绑定的应用而言,实际上有多种方案都可以做到与其等效的效果。例如:

  • 使用 @Component 注解搭配 @ConfigurationProperties 注解使用。
  • 使用 @Bean 注解搭配 @ConfigurationProperties@Configuration 注解使用。

相较于上述两种方式,使用 @EnableConfigurationProperties 注解,可以不再需要在配置属性 Bean 的上方再添加 @Component 或者在配置类中通过 @Bean 声明某个配置属性 Bean。

@EnableConfigurationProperties 注解的优点是方便将配置集中在一起进行管理,从而清晰的看到实现统一绑定配置的 Bean,而无需在自定义的 Bean 中逐个查找。例如:

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({
        SchoolProperties.class,
        HomeProperties.class
})
public class CustomConfig {

    // 其他的配置

}

上例中,可以十分清晰、明确地观察到 SchoolPropertiesHomeProperties 在应用程序中进行了配置绑定。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JiaHao汤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值