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

Environment实现原理

在基于SpringBoot开发的应用中,我们常常会在application.propertiesapplication-xxx.propertiesapplication.ymlapplication-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;
 }
}

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

ConfigurableEnvironment继承EnvironmentEnvironment继承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配置中心客户端是如何与SpringBoot整合的?

开源的Apollo配置中心默认启动就是通过BeanFactoryPostProcessor来扩展apollo上的配置到Spring的Environment中,
@EnableApolloConfig 注解向Spring中导入了bean com.ctrip.framework.apollo.spring.config.PropertySourcesProcessorPropertySourcesProcessor同时实现了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扩展外部化配置的原理解析的文章就介绍到这了,更多相关SpringBoot扩展外部化配置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 详解SpringBoot配置文件启动时动态配置参数方法

    序言 当我们要同时启用多个项目而又要使用不同端口或者变换配置属性时,我们可以在配置文件中设置${变量名}的变量来获取启动时传入的参数,从而实现了动态配置参数,使启用项目更加灵活 例子 server: port: ${PORT:50101} #服务端口 spring: application: name: xc‐govern‐center #指定服务名 eureka: client: registerWithEureka: true #服务注册,是否将自己注册到Eureka服务中 fetchReg

  • SpringBoot在yml配置文件中配置druid的操作

    最新版的druid和旧版在filter配置方面有些不同,以下是旧版druid中配置filter: spring: ##数据库连接信息 datasource: url: jdbc:mysql://localhost:3306/young username: root password: root driver-class-name: com.mysql.jdbc.Driver ###################以下为druid增加的配置########################### t

  • SpringBoot同一接口多个实现类配置的实例详解

    SpringBoot项目中可能出现一个接口有多个实现类的情况,如果不进行配置,注入接口时编译器不知道要注入哪个实现类就会报错,因此需要进行配置.以下进行举例: 接口如下: public interface NoticeService { public String noticeUser(Long id); } 两个实现类如下: @Service public class NoticeServiceImpl1 implements NoticeService { public String not

  • 详解关于SpringBoot的外部化配置使用记录

    更新: 工作中突然想起来,关于Yaml的使用,并不属于Spring的范畴,是org.yaml.snakeyaml处理的.所以yaml的使用应该参考官方,不过貌似打不开... Spring利用snakeyaml将配置解析成PropertySource,然后写入到Environment,就能使用了 记录下使用SpringBoot配置时遇到的一些麻烦,虽然这种麻烦是因为知识匮乏导致的. 记录下避免一段时间后自己又给忘记了,以防万一. 如果放到博客里能帮助到遇到同样问题的同志,自是极好! SpringB

  • SpringBoot外部化配置使用Plus版的方法示例

    PS: 之前写过一篇关于 SpringBoo 中使用配置文件的一些姿势,不过嘛,有句话(我)说的好:曾见小桥流水,未睹观音坐莲!所以再写一篇增强版,以便记录. 序言 上一篇博客记录,主要集中在具体的配置内容,也就是使用 @ConfigurationProperties 这个注解来进行配置与结构化对象的绑定,虽然也顺带说了下 @Value 的使用以及其区别. 在这篇记录中,打算从总览,鸟瞰的俯视视角,来从整体上对 SpringBoot ,乃至 Spring Framework 对于外部化配置文件处

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

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

  • Springboot自动加载配置的原理解析

    目录 1.springboot自动配置的原理初探 2. 补充扩展(解释为什么引用的包都报红错了,项目还能启动) 3.又一个问题 总结 1.springboot自动配置的原理初探 以下注解都在springboot的自动化配置包中:spring-boot-autoconfigure.读者朋友可以跟着一下步骤走一遍,应该对自动配置就有一定的认知了. 1.springboot程序的入口是在启动类,该类有个关键注解SpringBootApplication @Target(ElementType.TYPE

  • Spring Boot外部化配置实战解析

    一.流程分析 1.1 入口程序 在 SpringApplication#run(String... args) 方法中,外部化配置关键流程分为以下四步 public ConfigurableApplicationContext run(String... args) { ... SpringApplicationRunListeners listeners = getRunListeners(args); // 1 listeners.starting(); try { ApplicationA

  • Spring boot读取外部化配置的方法

    目录 1. Properties / YAML 1.1 Environment 1.2 Value注解 2. 自定义Properties文件 3. 其他命令参数 总结 这篇文章我们主要讨论 Spring Boot 的外部化配置功能,该功能主要是通过外部的配置资源实现与代码的相互配合,来避免硬编码,提供应用数据或行为变化的灵活性.本文主要记录读取外部化配置的几种常见的操作方式,相关原理不在此记录. 1. Properties / YAML 我们一般会将相关配置信息写在Properties / YA

  • SpringCloud配置刷新原理解析

    我们知道在SpringCloud中,当配置变更时,我们通过访问http://xxxx/refresh,可以在不启动服务的情况下获取最新的配置,那么它是如何做到的呢,当我们更改数据库配置并刷新后,如何能获取最新的数据源对象呢?下面我们看SpringCloud如何做到的. 一.环境变化 1.1.关于ContextRefresher 当我们访问/refresh时,会被RefreshEndpoint类所处理.我们来看源代码: /* * Copyright 2013-2014 the original a

  • 浅谈SpringBoot内嵌Tomcat的实现原理解析

    一.序言 使用SpringBoot经常会使用内嵌的tomcat做为项目的启动容器,本文将从源码的角度出发,剖析SpringBoot内嵌Tomcat的实现原理,讨论Tomcat何时创建.何时启动以及怎么启动. 二.引入Tomcat组件 导入依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId&

  • Spring外部化配置的几种技巧分享

    目录 正文 Envrionment 获取外部配置 修改Spring默认配置文件名称 Value注解配置来源 外部化配置文件优先级问题 Autowire注入ConfigurableEnvrionment ApplicationInitialiazer 配置 总结 正文 Envrionment 获取外部配置 @Log4j2 @SpringBootApplication public class ConfigurationApplication { public static void main(St

  • 大厂禁止SpringBoot在项目使用Tomcat容器原理解析

    目录 前言 SpringBoot中的Tomcat容器 SpringBoot设置Undertow Tomcat与Undertow的优劣对比 最后 前言 在SpringBoot框架中,我们使用最多的是Tomcat,这是SpringBoot默认的容器技术,而且是内嵌式的Tomcat.同时,SpringBoot也支持Undertow容器,我们可以很方便的用Undertow替换Tomcat,而Undertow的性能和内存使用方面都优于Tomcat,那我们如何使用Undertow技术呢?本文将为大家细细讲解

随机推荐