概述
注解@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