您好,登录后才能下订单哦!
这篇文章给大家分享的是有关SpringBoot扩展外部化配置的原理是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
在基于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<PropertySource<?>>集合。

public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
void setActiveProfiles(String... profiles);
void addActiveProfile(String profile);
void setDefaultProfiles(String... profiles);
//MutablePropertySources 内部实际上就是**List<PropertySource<?>>集合
MutablePropertySources getPropertySources();
Map<String, Object> getSystemProperties();
Map<String, Object> getSystemEnvironment();
void merge(ConfigurableEnvironment parent);
}PropertySource是什么呢?
其实就是一个key-value集合,key就是一个配置项,value就是配置的值。
例如: 通过System.getProperties()得到的系统属性就是一种类型的PropertySource,通过application.yml配置的属性是另一种属性资源。当调用env.getProperty()获取属性值时,会遍历PropertySource集合,只要有一个PropertySource中有对应属性值则不再继续遍历查找,所以在集合中越靠前的属性优先级越高。
获取某个配置项值的访问方式,源码如下:org.springframework.core.env.PropertySourcesPropertyResolver#getProperty(java.lang.String, java.lang.Class<T>, boolean)
protected <T> T getProperty(String key, Class<T> 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
但是在4.BeanDefinitionRegistryPostProcessor和5.BeanFactoryPostProcessor中扩展时机比较晚,这个时候已经执行完包扫描,如果在这个时机添加自己的外部化配置,对于注解@ConditionalOnProperty可能大部分不会生效。
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中的配置项。
感谢各位的阅读!关于“SpringBoot扩展外部化配置的原理是什么”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。