springboot使用@ConfigurationProperties实现自动绑定配置参数属性

 更新时间:2025年05月04日 21:24:51   作者:曹朋羽  
这篇文章主要介绍了springboot使用@ConfigurationProperties实现自动绑定配置参数属性,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

@ConfigurationProperties使用

@ConfigurationProperties是 springboot提供用于将配置文件中的属性值映射到 Java bean对象上。通过使用该注解,我们可以方便地将属性文件中的值绑定到一个实例化的类对象上,从而方便地在应用程序中使用这些属性。

@ConfigurationProperties注解有一个参数prefix用来指定属性公共前缀

@Configuration
@ConfigurationProperties(prefix = "myconfig")
@Data
public class MyConfigProperty {
    private int port;
    //找不到的属性不会注入
    private String hhh;
}

一般作为属性注入对象,首先定义成一个@Configuration。然后使用@ConfigurationProperties指定关联属性的前缀。

这样如果配置文件中有myconfig.port的值就会自动绑定到MyConfigProperty类的port属性上。前提要有对应的set方法。

除了在类上标注外,还可以在@Bean方法上

@Configuration
public class MyConfigByMethod {
    @Bean
    @ConfigurationProperties(prefix = "myconfig")
    public MyConfig myConfig(){
        return  new MyConfig();
    }
}

观察spring的源码,还会使用@EnableConfigurationProperties引入被@ConfigurationProperties修饰的bean

框架自动装配解析

在springboot框架自动装配中有一个内置的用来处理@ConfigurationProperties注解的配置类ConfigurationPropertiesAutoConfiguration,该配置类引入@EnableConfigurationProperties,然后间接引入EnableConfigurationPropertiesRegistrar,EnableConfigurationPropertiesRegistrar在configuration初始化的时候会调用其registerBeanDefinitions()方法进行配置类中扩展beanDef的加载。

EnableConfigurationPropertiesRegistrar#registerBeanDefinitions

public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
		registerInfrastructureBeans(registry);
		registerMethodValidationExcludeFilter(registry);
		ConfigurationPropertiesBeanRegistrar beanRegistrar = new ConfigurationPropertiesBeanRegistrar(registry);
		getTypes(metadata).forEach(beanRegistrar::register);
	}

private Set<Class<?>> getTypes(AnnotationMetadata metadata) {
   return metadata.getAnnotations().stream(EnableConfigurationProperties.class)
         .flatMap((annotation) -> Arrays.stream(annotation.getClassArray(MergedAnnotation.VALUE)))
         .filter((type) -> void.class != type).collect(Collectors.toSet());
}
static void registerInfrastructureBeans(BeanDefinitionRegistry registry) {
		ConfigurationPropertiesBindingPostProcessor.register(registry);
		BoundConfigurationProperties.register(registry);
}

这里主要会完成两件事件:

1、registerInfrastructureBeans会将ConfigurationPropertiesBindingPostProcessor注册到容器中,这是一个后置处理其,属性的赋值会在其后置方法里完成。

2、注册合适的ConfigurationProperties类型bean, 当前metadata是正在初始化的Configuration类,然后从其注解上获取带有EnableConfigurationProperties注解作为bean定义加载到容器中。

来看几个自动装配的例子:

ServletWebServerFactoryAutoConfiguration

  • ServletWebServerFactoryAutoConfiguration上带有@EnableConfigurationProperties(ServerProperties.class)注解,则ServerProperties会作为一个bean进行处理。
  • ServerProperties上配置有@ConfigurationProperties(prefix = “server”, ignoreUnknownFields = true),我们场景的server.port属性就会注入到ServerProperties.port属性上。

DataSourceAutoConfiguration

@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {}

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties{}

DataSourceProperties会被做为一个bean加载,"spring.datasource"下的属性会注入到DataSourceProperties属性中。

ConfigurationPropertiesBindingPostProcessor

ConfigurationPropertiesBindingPostProcessor是一个bean后置处理器,在bean实例化后会调用其后置方法

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
   bind(ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName));
   return bean;
}

ConfigurationPropertiesBean.get()方法会判断当前bean是否有ConfigurationProperties注解,如果有会进行对应的属性绑定。

最后使用org.springframework.boot.context.properties.bind.Binder类进行属性绑定。

这里ConfigurationProperties会有两部分,一是框架通过autoConfig自动装配的,一种是我们自己显示使用@ConfigurationProperties修饰的bean。

这里看到我们在自定义@ConfigurationProperties时候不一定非用@Configuration进行修饰,只要当前类能被解析成一个bean,都会调用该后置方法进行对应配置属性的赋值。

属性元数据信息

可配置的属性在每个jar包META-INFO/spring-configuration-metadata.json文件。这样一般在IDEA配置application文件时候都能根据该文件里的元数据信息进行提示配置。

例如server.port配置在spring-boot-autoconfigure.jar包中

{
  "name": "server.port",
  "type": "java.lang.Integer",
  "description": "Server HTTP port.",
  "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties",
  "defaultValue": 8080
},

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别及设定serverTimezone的方法

    com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区

    这篇文章主要介绍了com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的区别以及设定serverTimezone的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-09-09
  • Java 字符串反转实现代码

    Java 字符串反转实现代码

    这篇文章主要介绍了 Java 字符串反转实现代码的相关资料,需要的朋友可以参考下
    2017-03-03
  • 基于Java注解(Annotation)的自定义注解入门介绍

    基于Java注解(Annotation)的自定义注解入门介绍

    要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法
    2013-04-04
  • 关于Gateway路由匹配规则解读

    关于Gateway路由匹配规则解读

    本文详细介绍了SpringCloudGateway的路由匹配规则,包括基本概念、常用属性、实际应用以及注意事项,路由匹配规则决定了请求如何被转发到目标服务,是Gateway的核心功能之一,在配置路由时需要注意顺序、性能和安全性
    2025-02-02
  • tio-boot框架整合ehcache实现过程示例

    tio-boot框架整合ehcache实现过程示例

    这篇文章主要为大家介绍了tio-boot框架整合ehcache实现过程示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Java读写Cookie记录的方法

    Java读写Cookie记录的方法

    这篇文章主要介绍了Java读写Cookie记录的方法,实例分析了java针对cookie记录读取与写入的技巧,需要的朋友可以参考下
    2015-05-05
  • IntelliJ IDEA使用SVN分支的简单介绍

    IntelliJ IDEA使用SVN分支的简单介绍

    今天小编就为大家分享一篇关于IntelliJ IDEA使用SVN分支的简单介绍,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10
  • Spring Boot 集成 RocketMQ 全流程指南(从依赖引入到消息收发)

    Spring Boot 集成 RocketMQ 全流程指南(从依赖引入到消息收发

    本文将通过 手动连接 和 配置连接 两种方式,详细讲解如何在 Spring Boot 中集成 RocketMQ,实现消息的同步与异步发送,并提供完整示例代码,感兴趣的朋友一起看看吧
    2025-04-04
  • Spring boot随机端口你都不会还怎么动态扩容

    Spring boot随机端口你都不会还怎么动态扩容

    这篇文章主要介绍了Spring boot随机端口你都不会还怎么动态扩容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • Java注解详细介绍

    Java注解详细介绍

    这篇文章主要介绍了Java注解详细介绍,本文讲解了Java注解是什么、Java注解基础知识、Java注解类型、定义Java注解类型的注意事项等内容,需要的朋友可以参考下
    2014-09-09

最新评论