Spring Boot 配置文件加载的优先级和指定多个外部配置文件

项目配置很多,所以对配置归类到了不同的配置文件中,如下:
在这里插入图片描述
springboot 默认加载的配置文件为 application.properties ,为了正常加载其他配置文件,在启动类上做了如下引用处理:

@SpringBootApplication
@PropertySources({ 
	 @PropertySource(value = "mybatis.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "common.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "message.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "mail.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "eureka-client.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "zipkin.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "redis.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "xxljob.properties", ignoreResourceNotFound = true),
	 @PropertySource(value = "feign.properties", ignoreResourceNotFound = true)
})
public class StartApplication {
	
	public static void main(String[] args) {
		SpringApplication.run(StartApplication.class, args);
	}
	
}

这样以来,需求满足了,项目启动和运行也都没有问题。
但是配置文件中的配置在不同环境部署的时候可能是有差异的,比如mybatis中的数据库连接信息。
而我们对springboot打包后形成了一个jar包文件,需要对差异化的配置进行修改,这样有两种处理办法:
一、创建一个 application.properties 配置文件,和 jar 包文件放一起或者放在 jar 包文件同级的 config 目录中(config 为固定名字),在 application 配置文件中填写差异化配置即可,因为这里的配置会覆盖jar中的配置,然后直接 java -jar xxxxx.jar 启动即可。

二、和我们代码结构一样,分别创建不同的配置文件,例如我们需要对 mybatis 文件的配置进行修改,然后我们创建了一个 mybatis.properties 配置文件,并且在里面覆盖配置了数据库连接信息。此时启动 springboot 的 jar 包的命令就要有所改变了,如下命令指定 spring.config.name,可以使用多个名称,注意一定要带上 application,否则内部默认的 application 就不会被加载了:

java -jar xxxxxx.jar --spring.config.name=application,mybatis

附 springboot 加载配置文件的优先级顺序:

jar目录:./config/
jar包目录:./
工程根目录:./config/
工程根目录:./
依赖的其他jar包或src代码目录:classpath:/config/
依赖的其他jar包或src代码目录:classpath:/

加载的优先级顺序是从上向下加载,并且所有的文件都会被加载,高优先级的内容会覆盖底优先级的内容,形成互补配置。


(END)

猜你喜欢

转载自blog.csdn.net/catoop/article/details/107641026