概述
注解@ConfigurationProperties的使用举例 :
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
// ServerProperties 是一个配置属性对象,会以一个bean的形式注册到容器
public class ServerProperties {
/**
* Server HTTP port.
*/
private Integer port;
/**
* Network address to which the server should bind.
*/
private InetAddress address;
// ...
}
当在一个bean组件上使用了@ConfigurationProperties注解时,指定的配置属性将会被设置到该bean。这一注解背后的工作机制,主要是由框架通过BeanPostProcessor ConfigurationPropertiesBindingPostProcessor来完成的。ConfigurationPropertiesBindingPostProcessor的作用是绑定PropertySources到@ConfigurationProperties注解的bean实例。这是一个框架内部工具,在实例化每一个bean时,框架会使用它将@ConfigurationProperties注解中指定前缀的外部配置属性项加载进来设置到bean相应的属性上。这里的PropertySources能够从上下文中的Environment对象获取外部配置属性项。
针对上面ServerProperties配置属性对象的例子,可以认为ConfigurationPropertiesBindingPostProcessor的效果是:
- 输入 :
ServerProperties配置属性对象,属性值尚未填充 - 处理 :
ConfigurationPropertiesBindingPostProcessor获取@ConfigurationProperties注解中prefix值,也就是server,获取外部配置文件中前缀为server的配置项,设置ServerProperties配置属性对象对应的成员变量 - 输出 :
ServerProperties配置属性对象,属性值已经填充 (其实就是输入对象,不过属性被填充)
关于 ConfigurationPropertiesBindingPostProcessor更进一步的工作原理,可以参考以下分析 :
Spring BeanPostProcessor : ConfigurationPropertiesBindingPostProcessor
参考文章
Springboot Servlet Web 项目中内置BeanPostProcessor清单
Spring BeanPostProcessor : ConfigurationPropertiesBindingPostProcessor

本文解析了@ConfigurationProperties注解的使用方式及原理,详细介绍了如何通过该注解将外部配置属性绑定到Spring Boot应用的配置属性对象上,实现配置的灵活管理和注入。
2万+

被折叠的 条评论
为什么被折叠?



