SpringBoot 环境与spring应用绑定之 bindToSpringApplication方法剖析

分享 未结 0 5445
KSE-music
KSE-music LV4 2018-08-15
悬赏:20积分
一、简要描述
	protected void bindToSpringApplication(ConfigurableEnvironment environment,
SpringApplication application) {
//构建一个属性配置工厂实例,其中构造参数就是需要绑定属性的目标对象,我们这里就是正在启动的Spring应用
PropertiesConfigurationFactory<SpringApplication> binder = new PropertiesConfigurationFactory<SpringApplication>(
application);//它是工厂bean,作用:验证一些属性,并将其绑定到指定类型的目标对象上,同时运行校验器(非必须)
binder.setTargetName("spring.main");//设置目标名称,即spring应用的前缀名称
binder.setConversionService(this.conversionService);//设置属性转换服务,比如:集合转数组、集合转对象......,很显然是为了在赋值属性值的时候转换成合适的类型绑定
binder.setPropertySources(environment.getPropertySources());//设置属性源即MutablePropertySources
try {
binder.bindPropertiesToTarget();//开始绑定属性到目标对象上
}
catch (BindException ex) {
throw new IllegalStateException("Cannot bind to SpringApplication", ex);
}
}
知识点:FactoryBean与BeanFactory的区别?
再开始进入绑定过程之前,我们顺便来看一下属性配置工厂的属性,如下所示:


1、bindPropertiesToTarget();该方法首先将开始绑定标志位置为true,然后又调用了方法doBindPropertiesToTarget();

2、doBindPropertiesToTarget();
该方法中首先构建了一个数据绑定对象类型RelaxedDataBinder,即表示属性字段的匹配是比较松散的,如:你可以用下划线或者驼峰都可以
其次就是为数据绑定对象设置一些属性,如:属性验证器,数据类型装换服务等等。

Iterable<String> relaxedTargetNames = getRelaxedTargetNames();获取松散的目标名称,也就是获取更多字段名称,如:小写字母转大写,点号变成下划线等等。这里讲spring.main变成了七种格式字段如下:


Set<String> names = getNames(relaxedTargetNames);该方法主要是通过内省获取目标对象全部属性字段(SpringApplication里全部字段),然后和spring.main组合生成最终属性字段


PropertyValues propertyValues = getPropertySourcesPropertyValues(names,relaxedTargetNames);
该方法主要就是讲属性源转换属性值,通过属性名称匹配将得到属性值(不仅仅是存储了name value,见org.springframework.beans.PropertyValue)用于接下来的属性赋值

dataBinder.bind(propertyValues);
因为这里环境的属性源每一个匹配目标对象,所以下面的绑定都没了。

最后还是检查是否存在错误的数据绑定。
回帖
  • 消灭零回复