springboot的jar包启用外部配置文件

863 阅读1分钟

一、场景再现

springboot打成jar后,想要替换jar内部application.properties的配置的值,有以下两个限制条件:

  1. 不方便重新打包
  2. 不方便在java -jar xxx.jar后面增加 --xxx.xxx=xxx的配置(比如密码)
  3. 想要使用外部的一个配置文件,使得外部的配置文件的值覆盖jar内部配置的值

二、方案

当前项目下的配置文件如下:

classpath:/config/application.yml

spring:
  profiles:
    active: dev
server:
  port: 8081

classpath:/config/application-dev.yml

parent:
  username: source
  password: sourcepass
  state:

当前目标想要使用外部配置文件覆盖 parent.password 和 parent.state 其他配置不变

  1. 外部创建文件

在外部系统中 /test/config 增加配置 application-ext.properties

parent.password=123456
parent.state=target
  1. 变更启动命令
java -jar xxx.jar --spring.profiles.active=dev,ext --spring.config.location=classpath:/config/,file:/test/config/

替换前为:

java -jar xxx.jar --spring.profiles.active=dev

image.png

替换后为:

java -jar xxx.jar --spring.profiles.active=dev,ext --spring.config.location=classpath:/config/,file:/test/config/

image 1.png