在环境或应用程序上下文启动之前对其进行自定义

2023-05-16

 

目录

 

官网文档

71.3 Customize the Environment or ApplicationContext before it starts

翻译

71.3 在环境或应用程序上下文启动之前对其进行自定义


 

官网文档

71.3 Customize the Environment or ApplicationContext before it starts

SpringApplication has ApplicationListeners and ApplicationContextInitializers that are used to apply customizations to the context or environment. Spring Boot loads a number of such customizations for use internally from META-INF/spring.factories. There is more than one way to register additional ones:

  • Programmatically per application by calling the addListeners and addInitializers methods on SpringApplication before you run it.
  • Declaratively per application by setting context.initializer.classes or context.listener.classes.
  • Declaratively for all applications by adding a META-INF/spring.factories and packaging a jar file that the applications all use as a library.

The SpringApplication sends some special ApplicationEvents to the listeners (even some before the context is created), and then registers the listeners for events published by the ApplicationContext as well. See Section 23.5, “Application events and listeners” in the ‘Spring Boot features’ section for a complete list.

It is also possible to customize the Environment before the application context is refreshed using EnvironmentPostProcessor. Each implementation should be registered in META-INF/spring.factories:

org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor

The implementation can load arbitrary files and add them to the Environment. For instance, this example loads a YAML configuration file from the classpath:

public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {

	private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment,
			SpringApplication application) {
		Resource path = new ClassPathResource("com/example/myapp/config.yml");
		PropertySource<?> propertySource = loadYaml(path);
		environment.getPropertySources().addLast(propertySource);
	}

	private PropertySource<?> loadYaml(Resource path) {
		if (!path.exists()) {
			throw new IllegalArgumentException("Resource " + path + " does not exist");
		}
		try {
			return this.loader.load("custom-resource", path, null);
		}
		catch (IOException ex) {
			throw new IllegalStateException(
					"Failed to load yaml configuration from " + path, ex);
		}
	}

}
[Tip]

The Environment will already have been prepared with all the usual property sources that Spring Boot loads by default. It is therefore possible to get the location of the file from the environment. This example adds the custom-resource property source at the end of the list so that a key defined in any of the usual other locations takes precedence. A custom implementation may obviously defines another order.

[Note]

While using @PropertySource on your @SpringBootApplication seems convenient and easy enough to load a custom resource in the Environment, we do not recommend it as Spring Boot prepares the Environment before the ApplicationContext is refreshed. Any key defined via @PropertySource will be loaded too late to have any effect on auto-configuration.

翻译

71.3 在环境或应用程序上下文启动之前对其进行自定义

SpringApplication具有ApplicationListeners和ApplicationContextInitializers属性,

public class SpringApplication {
...
private List<ApplicationContextInitializer<?>> initializers;

private List<ApplicationListener<?>> listeners;
...
}

用于对上下文或者环境进行自定义。SpringBoot从META-INF/Spring.Factories中加载了许多这样的定制以供内部使用。有多种方法可以注册其他方法:

  • 通过在运行SpringApplication之前对其调用addListeners和addInitializers方法,以编程方式为每个应用程序提供支持。

  • 通过设置context.initializer.classes或context.listener.classes声明每个应用程序。

  • 通过添加META-INF/spring.factures并打包应用程序都用作库的JAR文件,声明性地针对所有应用程序。

SpringApplication向监听器发送一些特殊的applicationEvents(甚至在创建上下文之前发送一些),然后为applicationContext发布的事件注册监听器。有关完整列表,请参阅“Spring引导功能”部分的第23.5节“应用程序事件和侦听器”。

还可以在使用EnvironmentPostProcessor自定义环境在刷新应用程序上下文之前。每个实现都应该在META-INF/Spring.Factories中注册:

org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor

实现可以加载任意文件并将其添加到环境中。例如,本例从类路径加载yaml配置文件:

public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {

	private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment,
			SpringApplication application) {
		Resource path = new ClassPathResource("com/example/myapp/config.yml");
		PropertySource<?> propertySource = loadYaml(path);
		environment.getPropertySources().addLast(propertySource);
	}

	private PropertySource<?> loadYaml(Resource path) {
		if (!path.exists()) {
			throw new IllegalArgumentException("Resource " + path + " does not exist");
		}
		try {
			return this.loader.load("custom-resource", path, null);
		}
		catch (IOException ex) {
			throw new IllegalStateException(
					"Failed to load yaml configuration from " + path, ex);
		}
	}

}

 环境已经准备好了所有通常的属性源,默认情况下Spring引导加载这些属性源。因此,可以从环境中获取文件的位置。此示例将自定义资源属性源添加到列表的末尾,以便在任何通常的其他位置中定义的键优先。自定义实现显然可以定义另一个顺序。

[Note]虽然在@SpringBootApplication 上使用@PropertySource似乎非常方便和容易,可以在环境中加载自定义资源,但我们不建议这样做,因为在刷新ApplicationContext 之前,Spring boot会准备好环境。通过@PropertySource定义的任何键将被加载太晚,无法对自动配置产生任何影响。

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在环境或应用程序上下文启动之前对其进行自定义 的相关文章

  • Python+Flask实现股价查询系统。Python绘制股票k线走势

    文章目录 一 实现效果图二 实现思路1 获取数据 2 可视化数据三 源码获取 一 实现效果图 打开默认显示半年线 xff0c 可以通过可视化类型选择可视化k线图 高低点等 xff08 目前只完成了初版 xff0c 当查询的股票数据返回为空时
  • typeHandlers 类型处理器

    类型转换器官网地址 无论是 MyBatis 在预处理语句 xff08 PreparedStatement xff09 中设置一个参数时 xff0c 还是从结果集中取出一个值时 xff0c 都会用类型处理器将获取的值以合适的方式转换成 Jav
  • idea创建父子工程

    new 一个project xff0c 删除src xff0c 只保留pom文件 xff0c 作为主工程 webparent xff0c 工程目录D ideaProjects self multimodule xff1b 右键点击上面创建的
  • css基础

    层叠次序 当同一个 HTML 元素被不止一个样式定义时 xff0c 会使用哪个样式呢 xff1f 一般而言 xff0c 所有的样式会根据下面的规则层叠于一个新的虚拟样式表中 xff0c 其中数字 4 拥有最高的优先权 浏览器缺省设置外部样式
  • spring官网下载jar包

    http repo spring io release org springframework spring 查找方法 xff1a https spring io gt 点击 project https spring io projects
  • idea快捷键

    Intellij IDEA神器居然还藏着这些实用小技巧 xff0c 爽 xff01 xff01 xff01 自动补全返回值 可以引入变量 ctrl 43 alt 43 v Ctrl 43 或者 xff0c 可以跑到大括号的开头与结尾 Ctr
  • IDEA添加serialVersionUID

    打开IDEA中的 Setting gt Editor gt Inspections 选项中 xff0c java gt Serialization issues gt 将Serializable class without 39 seria
  • java序列化

    http www cnblogs com szlbm p 5504166 html Java对象表示方式1 xff1a 序列化 反序列化和transient关键字的作用 平时我们在Java内存中的对象 xff0c 是无 法进行IO操作或者网
  • Java之Collections.emptyList()、emptySet()、emptyMap()的作用和好处以及要注意的地方。

    https blog csdn net qq 27093465 article details 65444622 先说明一下好处有哪些 xff1a 1 xff0c 如果你想 new 一个空的 List xff0c 而这个 List 以后也不
  • java String ... valuese 什么意思

    jdk1 5的新特性 xff1a 变长变量 其实这种定义就类似一个数据的定义 xff0c 可以不用给它的长度加以限制 xff0c 可以传入任意多个参数 比用数据更灵活一些 xff0c 不会出现一些数组越界等的异常 如 xff1a getTy
  • debug技巧和使用

    介绍一种能debug到HashMap内部数据结构的方法 https blog csdn net victor cindy1 article details 52336983 1 这里以一个web工程为例 xff0c 点击图中按钮开始运行we
  • Linux中如何添加/删除FTP用户并设置权限?

    以阿里云服务器为例 xff0c 在linux中添加ftp用户 xff0c 并设置相应的权限 xff0c 操作步骤如下 xff1a 1 环境 xff1a ftp为vsftp 被设置用户名为test 被限制路径为 alidata www tes
  • 解析IOS二进制格式的bplist

    关于二进制格式的plist xff0c 搜到一篇博客 详解Binary Plist格式 xff0c 介绍的很详细 xff0c 但是结合github上关于一份解析bplist的代码通过结果实际来看 xff0c 博客中解析对象表的说明出现了问题
  • Java中的String,StringBuilder,StringBuffer三者的区别

    最近在学习Java的时候 xff0c 遇到了这样一个问题 xff0c 就是String StringBuilder以及StringBuffer这三个类之间有什么区别呢 xff0c 自己从网上搜索了一些资料 xff0c 有所了解了之后在这里整
  • SynthesizedAnnotation

    标识组合注解 该接口没有实现类 xff0c 具体用法待研究
  • autowire注解源码解析

    引用 xff1a https blog csdn net wang704987562 article details 80868368
  • ConcurrentHashMap解析

    https www cnblogs com ITtangtang p 3948786 html java util concurrent xff08 j u c xff09 源码阅读
  • Java中getResourceAsStream的用法

    https www cnblogs com macwhirr p 8116583 html 首先 xff0c Java中的getResourceAsStream有以下几种 xff1a 1 Class getResourceAsStream
  • Map var2 = this.bfgInstancesByKey; synchronized(this.bfgInstancesByKey) { 疑惑

    org springframework beans factory access SingletonBeanFactoryLocator useBeanFactory public BeanFactoryReference useBeanF
  • spring父子容器

    https www jb51 net article 132197 htm http www cnblogs com kevin yuan p 6404702 html https blog csdn net user xiangpeng

随机推荐

  • ContextLoaderListener与RequestContextListener配置问题

    https blog csdn net yanweju article details 70622313 在SSH2 SSM等web应用开发框架的配置过程中 xff0c 因为都要用到Spring xff0c 所以 xff0c 往往我们首先都
  • Class的isAssignableFrom方法

    https www cnblogs com hzhuxin p 7536671 html Class类的isAssignableFrom是个不常用的方法 xff0c 感觉这个方法的名字取得不是很好 xff0c 所以有必要在此解析一下 xff
  • dto层与model层的区别

    Model层是面向业务的 xff0c 我们是通过业务来定义Model的 而DTO是面向界面UI的 xff0c 是通过UI的需求来定义的 通过DTO我们实现了表现层与Model之间的解耦 xff0c 表现层不引用Model 如果开发过程中我们
  • 常用命令 ctags的使用

    1 命令ctags ctags的功能 xff1a 扫描指定的源文件 xff0c 找出其中所包含的语法元素 xff0c 并将找到的相关内容记录下来 ctags R 扫描当前目录及所有子目录 xff08 递归向下 xff09 中的源文件 结合v
  • idea 导入 maven依赖包的源码

    修改maven的版本为maven2 xff08 之前是maven3 xff09 勾选自动下载
  • Error java: 无法访问javax.servlet.ServletException 找不到javax.servlet.ServletException的类文件

    pom xml文件添加下面依赖 xff1a lt dependency gt lt groupId gt javax lt groupId gt lt artifactId gt javaee api lt artifactId gt lt
  • 如何看Spring源码

    https blog csdn net qq 27529917 article details 79209846 想要深入的熟悉了解Spring源码 xff0c 我觉得第一步就是要有一个能跑起来的极尽简单的框架 xff0c 下面我就教大家搭
  • AnnotationAwareOrderComparator

    https blog csdn net zhuqiuhui article details 82974026 AnnotationAwareOrderComparator简介 xff1a AnnotationAwareOrderCompar
  • HandlerInterceptor

    对SpringMVC有所了解的人肯定接触过HandlerInterceptor拦截器 xff0c HandlerInterceptor接口给我们提供了3个方法 xff1a xff08 1 xff09 preHandle 在执行control
  • spring源码阅读记录

    spring启动方式之一 xff1a 通过实现servlet3 0的Servlet容器初始化接口javax servlet ServletContainerInitializer xff0c 调用onStartup方法来启动项目 无web
  • IDEA将外来的jar包导入到maven项目中

    https blog csdn net baidu 32492845 article details 79173893 很多时候项目因为方便运行或者maven的dependency中到 xff0c 我们会直接将现有的jar包导入到项目中 x
  • intellij idea Jdk编译设置

    1 修改 Language level 和 Module SDK 选择 File gt project Structure gt Modules xff0c 选择项目修改 Sources 选项卡下的 Language level 及 Dep
  • JDK8新特性:函数式接口@FunctionalInterface的使用说明

    https blog csdn net aitangyong article details 54137067 我们常用的一些接口Callable Runnable Comparator等在JDK8中都添加了 64 FunctionalIn
  • JDK8新特性:接口的静态方法和默认方法

    https blog csdn net aitangyong article details 54134385 在jdk8之前 xff0c interface之中可以定义变量和方法 xff0c 变量必须是public static fina
  • 如何使用github和git进行团队合作开发(队友和owner的仓库连接)

    折腾了两天终于搞懂了一个团队开发一个项目 xff0c 在github和git下该如何操作 xff0c 本文就简单总结一下我的过程吧 xff0c 希望对大家有帮助 1 首先确定一个项目拥有者 xff0c 即你们一个团队的项目都上传到他的git
  • springboot源码阅读一

    目录 入口 SpringApplication 部分参数初始化 SpringApplication initialize方法 SpringApplication run方法 StopWatch java awt headless系统设定 入
  • idea Maven项目找不到相关依赖包(红色波浪线)

    方案一 修改pom 配置文件 xff0c 讲标红的依赖先删除 xff0c 并点击reimport 之后重新加上出错的依赖 xff0c 再reimport 方案二 从删除本地仓库中的文件目录 xff0c 强制 maven 重新下载该包
  • 自定义FailureAnalyzer

    目录 介绍 代码示例 介绍 FailureAnalyzer是一种很好的方式在启动时拦截异常并将其转换为易读的消息 xff0c 并将其包含在FailureAnalysis中 Spring Boot为应用程序上下文相关异常 JSR 303验证等
  • 自动配置故障排除

    目录 官网文档 71 2 Troubleshoot auto configuration 翻译 71 2 自动配置故障排除 官网文档 71 2 Troubleshoot auto configuration The Spring Boot
  • 在环境或应用程序上下文启动之前对其进行自定义

    目录 官网文档 71 3 Customize the Environment or ApplicationContext before it starts 翻译 71 3 在环境或应用程序上下文启动之前对其进行自定义 官网文档 71 3 C