SpringBoot中如何扩展外部化配置中心

2024-08-31 18:08

本文主要是介绍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;@Autowiredprivate Environment env;@Autowiredprivate 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); //truereturn 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)
    • ApplicationListener< org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent> EnvironmentPostProcessorApplicationListener
      • org.springframework.boot.env.EnvironmentPostProcessor
        • org.springframework.boot.context.config.ConfigDataLoader
          • org.springframework.boot.env.PropertySourceLoader
  2. org.springframework.context.ApplicationContextInitializer#initialize
  3. org.springframework.boot.SpringApplicationRunListener#contextPrepared
    • org.springframework.boot.context.event.ApplicationPreparedEvent
  4. org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
  5. org.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中如何扩展外部化配置中心的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1124621

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注