SpringBoot扩展外部化配置的原理解析

网友投稿 709 2023-02-06

SpringBoot扩展外部化配置的原理解析

SpringBoot扩展外部化配置的原理解析

Environment实现原理

在基于SpringBoot开发的应用中,我们常常会在application.properties、application-xxx.properties、application.yml、application-xxx.yml等配置文件中设置一些属性值,然后通过@Value、@ConfigurationProperties等注解获取,或者采用编码的方式通过Environment获取。

# application.properties

my.config.appId=demo

@RestController

public class WebController {

@Value("${my.config.appId}")

private String appId;

@Autowired

private Environment env;

@Autowired

private ConfigurableEnvironment environment;

@GetMapping("/appInfo")

public String appInfo() {

System.out.println(environment.getProperty("my.config.appId"));

System.out.println(env.getProperty("my.config.appId"));

System.out.println(appId);

System.out.println(env == environment); //true

return appId;

}

}

实际上env和environment是同一个对象,在Spring中ConfigurableEnvironment是Environment的子类,具体实现类全部是通过implements ConfigurableEnvironment接口来实现,所以所有可以拿到Environment接口地方都可以强制转换为ConfigurableEnvironment。

ConfigurableEnvironment继承Environment,Environment继承PropertyResolver,主要提供了对属性获取方法,AbstractEnvironment做为抽象类实现了ConfigurableEnvironment接口方法,其内部是通过org.springframework.core.env.MutablePropertySources来保存不同类型的属性资源。而MutablePropertySources内部实际上就是List>集合。

public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {

void setActiveProfiles(String... profiles);

void addActiveProfile(String profile);

void setDefaultProfiles(String... profiles);

//MutablePropertySources 内部实际上就是**List>集合

MutablePropertySourhttp://ces getPropertySources();

Map getSystemProperties();

Map getSystemEnvironment();

void merge(ConfigurableEnvironment parent);

}

PropertySource是什么呢?

其实就是一个key-value集合,key就是一个配置项,value就是配置的值。

例如: 通过System.getProperties()得到的系统属性就是一种类型的PropertySource,通过application.yml配置的属性是另一种属性资源。vhlVUtLO当调用env.getProperty()获取属性值时,会遍历PropertySource集合,只要有一个PropertySource中有对应属性值则不再继续遍历查找,所以在集合中越靠前的属性优先级越高。

获取某个配置项值的访问方式,源码如下:

org.springframework.core.env.PropertySourcesPropertyResolver#getProperty(java.lang.String, java.lang.Class, boolean)

protected T getProperty(String key, Class targetValueType, boolean resolveNestedPlaceholders) {

if (this.propertySources != null) {

for (PropertySource> propertySource : this.propertySources) {

if (logger.isTraceEnabled()) {

logger.trace("Searching for key '" + key + "' in PropertySource '" + propertySource.getName() + "'");

}

Object value = propertySource.getProperty(key);

if (value != null) {

if (resolveNestedPlaceholders && value instanceof String) {

value = resolveNestedPlaceholders((String) value);

}

logKeyFound(key, propertySource, value);

return convertValueIfNecessary(value, targetValueType);

}

}

}

if (logger.isTraceEnabled()) {

logger.trace("Could not find key '" + key + "' in any property source");

}

return null;

}

如何扩展自己的外部化配置?

实际上我们可以利用SpringBoot中的扩展点,拿到ConfigurableEnvironment对象来获取到MutablePropertySources,添加自己的PropertySource就行,例如可以访问一个http接口,获取外部化配置。

扩展接口及优先级如下

梯形缩进表示内部调用了下面的接口实现

1.org.springframework.boot.SpringApplicationRunListener#environmentPrepared(ConfigurableBootstrapContext, ConfigurableEnvironment)

1.ApplicationListener< org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent> EnvironmentPostProcessorApplicationListener

1. org.springframework.boot.env.EnvironmentPostProcessor 1.org.springframework.boot.context.config.ConfigDataLoader 1.org.springframework.boot.env.PropertySourceLoader 1.org.springframework.context.ApplicationContextInitializer#initialize

1.org.springframework.boot.SpringApplicationRunListener#contextPrepared 4.org.springframework.boot.context.event.ApplicationPreparedEvent 5.org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistryorg.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory

但http://是在4.BeanDefinitionRegistryPostProcessor和5.BeanFactoryPostProcessor中扩展时机比较晚,这个时候已经执行完包扫描,如果在这个时机添加自己的外部化配置,对于注解@ConditionalOnProperty可能大部分不会生效。

Apollo配置中心客户端和SpringBoot的整合实现

Apollo配置中心客户端是如何与SpringBoot整合的?

开源的Apollo配置中心默认启动就是通过BeanFactoryPostProcessor来扩展apollo上的配置到Spring的Environment中,

@EnableApolloConfig 注解向Spring中导入了bean com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor,PropertySourcesProcessor同时实现了org.springframework.core.PriorityOrdered并设置了最高的执行优先级Ordered.HIGHEST_PRECEDENCE,但是由于包扫描已经在PropertySourcesProcessor之前执行完成,所以即使设置了最高优先级,同样无法解决在Spring执行包扫描阶段访问不到apllo上的配置问题。

因此在SpringBoot项目中,apollo提供了另一种启动方式,使用配置项apollo.bootstrap.enabled = true来解决,实现类为com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer,其主要是通过实现第2个扩展接口org.springframework.context.ApplicationContextInitializer来提前将apollo的PropertySource添加到Spring的Environment中。

这样我们就可以通过Environment来获取到apollo中的配置项值。而@ConditionalOnProperty则是从Environment获取属性值来判断的条件是否成立,因此使用该接口扩展Environment,@ConditionalOnProperty注解则可以在启动阶段正常访问到apollo中的配置项。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:无线上网安全管控前端(无线网安全技术)
下一篇:抖音APP运营模式的不足(抖音app运营模式的不足之处)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~