SpringBoot详细讲解多个配置文件的配置流程

2022-11-13 09:11:35 多个 配置文件 讲解

一般情况下,SpringBoot默认会在resource目录下生成一个配置文件(application.properties或application.yaml),但其实springboot允许配置多个配置文件(application.properties或application.yaml),但是这并不意味着这些配置文件一定会替换默认生成的配置文件,它们是互补的存在。如果在某些场景下需要把配置文件单独拿出来并且启动的时候加载进去,那么外部的配置文件将是一个很好的选择。

配置文件加载顺序

需要注意的是配置文件加载顺序加载顺序在springboot 2.4.0前后是不一样的。

springboot 2.4.0及其之前版本的配置文件加载顺序

file:./config/
file:./config
file:./config/
file:./
classpath:config/
classpath:

区别在于springboot 2.4.0之后的版本将file:./config8084file:./config配置文件

保持不变

server.port=8084
spring.application.name=file:./config/*/

修改启动类main方法在控制台打印server.error.path

public static void main(String[] args) {
		ConfigurableApplicationContext applicationContext = SpringApplication.run(MQApplication.class, args);
		ConfigurableEnvironment environment = applicationContext.getEnvironment();
		String property = environment.getProperty("spring.application.name");
		System.out.println("current spring.application.name="+property);
		String errorPath = environment.getProperty("server.error.path");
		System.out.println("errorPath="+errorPath);
	}

启动项目

从上面截图中可以发现三个配置文件中的所有属性都被加载出来了,而且优先级高的配置文件中的属性会覆盖优先级低的配置文件中的属性。

总结

springboot中可以配置多个配置文件,并且这些配置文件是可以共存的。当属性相同时,优先级高的配置文件会覆盖优先级低的配置文件中的属性;当属性不同时,最终的配置会取各个配置文件中属性的并集。

到此这篇关于SpringBoot详细讲解多个配置文件的配置流程的文章就介绍到这了,更多相关SpringBoot配置文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章