欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot外部化配置实战解析

程序员文章站 2023-01-08 18:33:16
一、流程分析 1.1 入口程序 在 springapplication#run(string... args) 方法中,外部化配置关键流程分为以下四步 pub...

一、流程分析

1.1 入口程序

在 springapplication#run(string... args) 方法中,外部化配置关键流程分为以下四步

public configurableapplicationcontext 

run(string... args) {

  ...

  springapplicationrunlisteners listeners = getrunlisteners(args); // 1

  listeners.starting();

  try {

    applicationarguments applicationarguments = new defaultapplicationarguments(

      args);

    configurableenvironment environment = prepareenvironment(listeners,

                                 applicationarguments); // 2

    configureignorebeaninfo(environment);

    banner printedbanner = printbanner(environment);

    context = createapplicationcontext();

    exceptionreporters = getspringfactoriesinstances(

      springbootexceptionreporter.class,

      new class[] { configurableapplicationcontext.class }, context);

    preparecontext(context, environment, listeners, applicationarguments,

            printedbanner); // 3

    refreshcontext(context); // 4

    afterrefresh(context, applicationarguments);

    stopwatch.stop();

    if (this.logstartupinfo) {

      new startupinfologger(this.mainapplicationclass)

        .logstarted(getapplicationlog(), stopwatch);

    }

    listeners.started(context);

    callrunners(context, applicationarguments);

  }

  ...

}

1.2 关键流程思维导图

Spring Boot外部化配置实战解析

1.3 关键流程详解

对入口程序中标记的四步,分析如下

1.3.1 springapplication#getrunlisteners

加载 meta-inf/spring.factories

获取 springapplicationrunlistener

的实例集合,存放的对象是 eventpublishingrunlistener 类型 以及自定义的 springapplicationrunlistener 实现类型

Spring Boot外部化配置实战解析

1.3.2 springapplication#prepareenvironment

prepareenvironment 方法中,主要的三步如下

private configurableenvironment 

prepareenvironment(springapplicationrunlisteners listeners,

  applicationarguments applicationarguments) {

  // create and configure the environment

  configurableenvironment environment = getorcreateenvironment(); // 2.1

  configureenvironment(environment, applicationarguments.getsourceargs()); // 2.2

  listeners.environmentprepared(environment); // 2.3

  ...

  return environment;

}

1) getorcreateenvironment 方法

在 webapplicationtype.servlet web应用类型下,会创建 standardservletenvironment,本文以 standardservletenvironment 为例,类的层次结构如下

Spring Boot外部化配置实战解析

当创建 standardservletenvironment,standardservletenvironment 父类 abstractenvironment 调用 customizepropertysources 方法,会执行 standardservletenvironment#customizepropertysources和 standardenvironment#customizepropertysources ,源码如下abstractenvironment

public abstractenvironment() {

  customizepropertysources(this.propertysources);

  if (logger.isdebugenabled()) {

    logger.debug("initialized " + getclass().getsimplename() + " with propertysources " + this.propertysources);

  }

}

standardservletenvironment#customizepropertysources

/** servlet context init parameters property source name: {@value} */

public static final 

stringservlet_context_property_source_name = "servletcontextinitparams";

/** servlet config init parameters property source name: {@value} */

public static final string 

servlet_config_property_source_name = "servletconfiginitparams";

/** jndi property source name: {@value} */

public static final string 

jndi_property_source_name = "jndiproperties";

@override

protected void customizepropertysources(mutablepropertysources propertysources) {

  propertysources.addlast(new stubpropertysource(servlet_config_property_source_name));

  propertysources.addlast(new stubpropertysource(servlet_context_property_source_name));

  if (jndilocatordelegate.isdefaultjndienvironmentavailable()) {

    propertysources.addlast(new jndipropertysource(jndi_property_source_name));

  }

  super.customizepropertysources(propertysources);

}

standardenvironment#customizepropertysources

/** system environment property source name: {@value} */

public static final string 

system_environment_property_source_name = "systemenvironment";

/** jvm system properties property source name: {@value} */

public static final string 

system_properties_property_source_name = "systemproperties";

@override

protected void customizepropertysources(mutablepropertysources propertysources) {

  propertysources.addlast(new mappropertysource(system_properties_property_source_name, getsystemproperties()));

  propertysources.addlast(new systemenvironmentpropertysource(system_environment_property_source_name,getsystemenvironment());

}

propertysources 顺序:

  • servletconfiginitparams
  • servletcontextinitparams
  • jndiproperties
  • systemproperties
  • systemenvironment

propertysources 与 propertysource 关系为 1 对 n

2) configureenvironment 方法

调用 configurepropertysources(environment, args), 在方法里面设置 environment 的 propertysources , 包含 defaultproperties 和

simplecommandlinepropertysource(commandlineargs),propertysources 添加 defaultproperties 到最后,添加

simplecommandlinepropertysource(commandlineargs)到最前面

propertysources 顺序:

  • commandlineargs
  • servletconfiginitparams
  • servletcontextinitparams
  • jndiproperties
  • systemproperties
  • systemenvironment
  • defaultproperties

3) listeners.environmentprepared 方法

会按优先级顺序遍历执行 springapplicationrunlistener#environmentprepared,比如 eventpublishingrunlistener 和 自定义的 springapplicationrunlistener

eventpublishingrunlistener 发布

applicationenvironmentpreparedevent 事件

configfileapplicationlistener 监听

applicationevent 事件 、处理 applicationenvironmentpreparedevent 事件,加载所有 environmentpostprocessor 包括自己,然后按照顺序进行方法回调

---configfileapplicationlistener#postprocessenvironment方法回调 ,然后addpropertysources 方法调用

randomvaluepropertysource#addtoenvironment,在 systemenvironment 后面添加 random,然后添加配置文件的属性源(详见源码configfileapplicationlistener.loader#load()

扩展点

  • 自定义 springapplicationrunlistener ,重写 environmentprepared 方法
  • 自定义 environmentpostprocessor
  • 自定义 applicationlistener 监听 applicationenvironmentpreparedevent 事件
  • configfileapplicationlistener,即是 environmentpostprocessor ,又是 applicationlistener ,类的层次结构如下

Spring Boot外部化配置实战解析

@override

public void onapplicationevent(applicationevent event) {

  // 处理 applicationenvironmentpreparedevent 事件

  if (event instanceof applicationenvironmentpreparedevent) {

    onapplicationenvironmentpreparedevent(

      (applicationenvironmentpreparedevent) event);

  }

  // 处理 applicationpreparedevent 事件

  if (event instanceof applicationpreparedevent) {

    onapplicationpreparedevent(event);

  }

}

private void onapplicationenvironmentpreparedevent(

  applicationenvironmentpreparedevent event) {

  // 加载 meta-inf/spring.factories 中配置的 environmentpostprocessor

  list

  // 加载自己 configfileapplicationlistener

  postprocessors.add(this);

  // 按照 ordered 进行优先级排序

  annotationawareordercomparator.sort(postprocessors);

  // 回调 environmentpostprocessor

  for (environmentpostprocessor postprocessor : postprocessors) {

    postprocessor.postprocessenvironment(event.getenvironment(),                      event.getspringapplication());

  }

}

list

  return springfactoriesloader.loadfactories(environmentpostprocessor.class,                        getclass().getclassloader());

}

@override

public void 

postprocessenvironment(configurableenvironment environment,

                  springapplication application) {

  addpropertysources(environment, application.getresourceloader());

}

/**

 * add config file property sources to the specified environment.

 * @param environment the environment to add source to

 * @param resourceloader the resource loader

 * @see 

#addpostprocessors(configurableapplicationcontext)

 */

protected void 

addpropertysources(configurableenvironment environment,

                 resourceloader resourceloader) {

randomvaluepropertysource.addtoenvironment(environment);

  // 添加配置文件的属性源

  new loader(environment, resourceloader).load();

}

randomvaluepropertysource

public static void 

addtoenvironment(configurableenvironment environment) {

  // 在 systemenvironment 后面添加 random

  environment.getpropertysources().addafter(

    standardenvironment.system_environment_property_source_name,

    new randomvaluepropertysource(random_property_source_name));

  logger.trace("randomvaluepropertysource add to environment");

}

添加配置文件的属性源:执行

new loader(environment, resourceloader).load();,

调用 load(profile, documentfilterfactory, documentconsumer)(getsearchlocations()

获取配置文件位置,可以指定通过 spring.config.additional-location 、spring.config.location 、spring.config.name 参数或者使用默认值 ), 然后调用 addloadedpropertysources -> addloadedpropertysource(加载 查找出来的 propertysource 到 propertysources,并确保放置到 defaultproperties 的前面 )

默认的查找位置,配置为

"classpath:/,classpath:/config/,file:./,file:./config/",查找顺序从后向前

propertysources 顺序:

  • commandlineargs
  • servletconfiginitparams
  • servletcontextinitparams
  • jndiproperties
  • systemproperties
  • systemenvironment
  • random
  • application.properties ...
  • defaultproperties

1.3.3 springapplication#preparecontext

preparecontext 方法中,主要的三步如下

private void 

preparecontext(configurableapplicationcontext context,

              configurableenvironment environment,

              springapplicationrunlisteners listeners,

              applicationarguments applicationarguments,

              banner printedbanner) {

  ...

  applyinitializers(context); // 3.1

  listeners.contextprepared(context); //3.2

  ...

  listeners.contextloaded(context); // 3.3

}

1)applyinitializers 方法

会遍历执行所有的 applicationcontextinitializer#initialize

扩展点

自定义 applicationcontextinitializer

2)listeners.contextprepared 方法

会按优先级顺序遍历执行 springapplicationrunlistener#contextprepared,比如 eventpublishingrunlistener 和 自定义的 springapplicationrunlistener

扩展点

自定义 springapplicationrunlistener ,重写 contextprepared 方法

3)listeners.contextloaded 方法

会按优先级顺序遍历执行 springapplicationrunlistener#contextloaded,比如 eventpublishingrunlistener 和 自定义的 springapplicationrunlistener

eventpublishingrunlistener 发布

applicationpreparedevent 事件

configfileapplicationlistener 监听

applicationevent 事件 处理

applicationpreparedevent 事件

扩展点

  • 自定义 springapplicationrunlistener ,重写 contextloaded 方法
  • 自定义 applicationlistener ,监听 applicationpreparedevent 事件

configfileapplicationlistener

@override

public void onapplicationevent(applicationevent event) {

  // 处理 applicationenvironmentpreparedevent 事件

  if (event instanceof 

applicationenvironmentpreparedevent) {

    onapplicationenvironmentpreparedevent(

      (applicationenvironmentpreparedevent) event);

  }

  // 处理 applicationpreparedevent 事件

  if (event instanceof applicationpreparedevent) {

    onapplicationpreparedevent(event);

  }

}

private void onapplicationpreparedevent(applicationevent event) {

  this.logger.replayto(configfileapplicationlistener.class);

  addpostprocessors(((applicationpreparedevent) event).getapplicationcontext());

}

// 添加 propertysourceorderingpostprocessor 处理器,配置 propertysources

protected void addpostprocessors(configurableapplicationcontext context) {

  context.addbeanfactorypostprocessor(

    new propertysourceorderingpostprocessor(context));

}

propertysourceorderingpostprocessor

// 回调处理(在配置类属性源解析)

@override

public void 

postprocessbeanfactory(configurablelistablebeanfactory beanfactory)

  throws beansexception {

  reordersources(this.context.getenvironment());

}

// 调整 propertysources 顺序,先删除 defaultproperties, 再把 defaultproperties 添加到最后

private void reordersources(configurableenvironment environment) {

  propertysource

    .remove(default_properties);

  if (defaultproperties != null) {

    environment.getpropertysources().addlast(defaultproperties);

  }

}

propertysourceorderingpostprocessor 是 beanfactorypostprocessor

1.3.4 springapplication#refreshcontext

会进行 @configuration 配置类属性源解析,处理 @propertysource annotations on your @configuration classes,但顺序是在 defaultproperties 之后,下面会把defaultproperties 调整到最后

abstractapplicationcontext#refresh 调用 invokebeanfactorypostprocessors(postprocessorregistrationdelegate#invokebeanfactorypostprocessors), 然后进行 beanfactorypostprocessor 的回调处理 ,比如 propertysourceorderingpostprocessor 的回调(源码见上文)

propertysources 顺序:

  • commandlineargs
  • servletconfiginitparams
  • servletcontextinitparams
  • jndiproperties
  • systemproperties
  • systemenvironment
  • random
  • application.properties ...
  • @propertysource annotations on your @configuration classes
  • defaultproperties

(不推荐使用这种方式,推荐使用在 refreshcontext 之前准备好,@propertysource 加载太晚,不会对自动配置产生任何影响)

二、扩展外部化配置属性源

2.1 基于 environmentpostprocessor 扩展

public class customenvironmentpostprocessor 

implements environmentpostprocessor

2.2 基于 applicationenvironmentpreparedevent 扩展

public class 

applicationenvironmentpreparedeventlistener implements applicationlistener

2.3 基于 springapplicationrunlistener 扩展

public class customspringapplicationrunlistener implements springapplicationrunlistener, ordered

可以重写方法 environmentprepared、contextprepared、contextloaded 进行扩展

2.4 基于 applicationcontextinitializer 扩展

public class customapplicationcontextinitializer implements applicationcontextinitializer

关于与 spring cloud config client 整合,对外部化配置加载的扩展(绑定到config server,使用远端的property sources 初始化 environment),参考源码propertysourcebootstrapconfiguration(是对 applicationcontextinitializer 的扩展)、configservicepropertysourcelocator#locate

获取远端的property sources是 resttemplate 通过向 http://{spring.cloud.config.uri}/{spring.application.name}/{spring.cloud.config.profile}/{spring.cloud.config.label} 发送 get 请求方式获取的

2.5 基于 applicationpreparedevent 扩展

public class applicationpreparedeventlistener 

implements applicationlistener

2.6 扩展实战

2.6.1 扩展配置

在 classpath 下添加配置文件 meta-inf/spring.factories, 内容如下

# spring application run listeners

org.springframework.boot.springapplicationrunlistener=\

springboot.propertysource.extend.listener.customspringapplicationrunlistener

# application context initializers

org.springframework.context.applicationcontextinitializer=\

springboot.propertysource.extend.initializer.customapplicationcontextinitializer

# application listeners

org.springframework.context.applicationlistener=\

springboot.propertysource.extend.event.listener.applicationenvironmentpreparedeventlistener,\

springboot.propertysource.extend.event.listener.applicationpreparedeventlistener

# environment post processors

org.springframework.boot.env.environmentpostprocessor=\

springboot.propertysource.extend.processor.customenvironmentpostprocessor

以上的扩展可以选取其中一种进行扩展,只是属性源的加载时机不太一样

2.6.2 扩展实例代码

propertysources 顺序:

propertysourcename: [applicationpreparedeventlistener], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [customspringapplicationrunlistener-contextloaded], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [customspringapplicationrunlistener-contextprepared], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [customapplicationcontextinitializer], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [bootstrapproperties], propertysourceclassname: [compositepropertysource]

propertysourcename: [configurationproperties], propertysourceclassname: [configurationpropertysourcespropertysource]

propertysourcename: [customspringapplicationrunlistener-environmentprepared], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [customenvironmentpostprocessor-dev-application], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationenvironmentpreparedeventlistener], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [commandlineargs], propertysourceclassname: [simplecommandlinepropertysource]

propertysourcename: [servletconfiginitparams], propertysourceclassname: [stubpropertysource]

propertysourcename: [servletcontextinitparams], propertysourceclassname: [servletcontextpropertysource]

propertysourcename: [systemproperties], propertysourceclassname: [mappropertysource]

propertysourcename: [systemenvironment], propertysourceclassname: [originawaresystemenvironmentpropertysource]

propertysourcename: [random], propertysourceclassname: [randomvaluepropertysource]

propertysourcename: [applicationconfig: [classpath:/extend/config/springapplicationrunlistener.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationconfig: [classpath:/extend/config/applicationlistener.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationconfig: [classpath:/extend/config/applicationcontextinitializer.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationconfig: [classpath:/extend/config/environmentpostprocessor.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationconfig: [classpath:/extend/config/application.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationconfig: [classpath:/extend/config/config.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [applicationconfig: [classpath:/application.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [springcloudclienthostinfo], propertysourceclassname: [mappropertysource]

propertysourcename: [applicationconfig: [classpath:/bootstrap.properties]], propertysourceclassname: [origintrackedmappropertysource]

propertysourcename: [propertysourceconfig], propertysourceclassname: [resourcepropertysource]

propertysourcename: [defaultproperties], propertysourceclassname: [mappropertysource]

bootstrapproperties 是 获取远端(config-server)的 property sources

加载顺序也可参考 http://{host}:{port}/actuator/env

propertysources 单元测试顺序:

  • @testpropertysource#properties
  • @springboottest#properties
  • @testpropertysource#locations

三、参考资料

https://docs.spring.io/spring-boot/docs/2.0.5.release/reference/htmlsingle/#boot-features-external-config

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。