SpringBoot源码深度解析(二):SpringBoot外部属性绑定原理详解

前言

我们继续分析SpringBoot的自动配置原理,这篇文章我们来分析@EnableConfigurationProperties和@ConfigurationProperties注解。探究下外部配置属性是如何被绑定到@ConfigurationProperties注解的类的属性中的。

举个例子:以配置web项目的服务器端口为例,如果我们将服务器端口配置为8081,那么我们会在application.properties文件中配置server.port=8081,此时该配置值8081就会被绑定到@ConfigurationProperties注解的类ServerProperties的属性port上,从而使配置生效。

正文

我们先来看看ServerProperties的源码,

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
	/**
	 * Server HTTP port.
	 */
	private Integer port;
	// ...
}

@ConfigurationProperties注解的作用就是将外部配置值绑定到其标注的类的属性上,可以作用于配置类或类的方法上。

我们再来看下服务器的自动配置类:ServletWebServerFactoryAutoConfiguration

@Configuration
@EnableConfigurationProperties(ServerProperties.class)
// ...
public class ServletWebServerFactoryAutoConfiguration {
	// ...
}

可以看到自动配置类上有一个注解:@EnableConfigurationProperties,该注解的主要作用就是为@ConfigurationProperties注解标注的类提供支持。

注解上通过@Import注解引入了EnableConfigurationPropertiesImportSelector类,这个类又引入了2个类ConfigurationPropertiesBeanRegistrar和ConfigurationPropertiesBindingPostProcessorRegistrar。

class EnableConfigurationPropertiesImportSelector implements ImportSelector {
        // IMPORTS数组即是要向spring容器中注册的bean
	private static final String[] IMPORTS = {
			ConfigurationPropertiesBeanRegistrar.class.getName(),
			ConfigurationPropertiesBindingPostProcessorRegistrar.class.getName() };

	@Override
	public String[] selectImports(AnnotationMetadata metadata) {
		// 返回ConfigurationPropertiesBeanRegistrar和ConfigurationPropertiesBindingPostProcessorRegistrar的全限定名
		// 即上面两个类将会被注册到Spring容器中
		return IMPORTS;
	}
}

真正执行属性绑定的逻辑就在这2个类中。有兴趣可以打个断点跟踪下源码。

总结

我们可以仿照SpringBoot的源码,来自定义属性类并绑定外部属性。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值