背景
在一个项目的开发过程中,通常伴随着多套环境:
本地环境 local、开发环境 dev、集成测试环境 test、用户接受测试环境 uat、预生产环境 pre、生产环境 prod。
真实的企业开发中,不会只开发一个独立的服务,而是多个微服务。面对多套环境,通常是”一套代码 + 配置中心“的方式,将代码编译打包后,在启动服务时或服务运行过程中,从配置中心读取配置,保证各个环境代码完全一致,仅配置不同。
配置文件
1.优先级
- 同一目录下:
properties
>yaml
>yml
如果放到config
目录下(如: src/main/resources/config/application.yml),config目录下的核心配置文件优先级会更高。 -
bootstrap.yml文件在纯粹的 Spring Boot 应用中不会生效,它只有在 Spring Cloud 下才会生效,在 Spring Cloud 中,应用会直接或间接依赖 spring-cloud-context,此时才会读取 bootstrap.yml 文件和 application.yml 文件,这种情况下 bootstrap.yml 优先级高于其他核心配置文件。
2.多环境两种配置方式
2.1 通过spring.profiles.active
spring:
profiles:
active: local
上面的配置指定了环境为 local,会加载 application-local.yml 文件。
在打包后,也可以在运行 jar 包时指定生效的环境
java -jar hero-springboot-demo.jar --spring.profiles.active=test
2.2 通过 Maven
application.yml 中 spring.profiles.active 配置一个占位符,在 Maven
打包时,通过具体的 profile
,替换 application.yml
中的占位符。
具体实现如下:
- application.yml 中使用占位符
spring:
profiles:
active: @env@
- pom.xml 中配置多环境
首先配置 profile:
<profiles>
<profile>
<id>local</id>
<properties>
<env>local</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
</profiles>
上面配置了三套 profile
,env
的值分别定义为 local
、dev
、test
,且 local 为默认激活。 接着在 中添加资源的处理:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>application-*.yml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.yml</include>
<include>application-${env}*.yml</include>
</includes>
</resource>
</resources>
<plugins>
...
</plugins>
</build>
filtering
设置为 true
,表示利用占位符进行替换。上面的配置先排除 application- 开头的资源文件,然后在根据生效的profile
对应的 env
的值,打包对应的 application-xxx.yml
文件。
通过maven配置的测试打包
两种方式:使用命令行 、 直接用IDEA。
- 命令行:
mvn clean package -Pdev ## -P后面就是对应的环境。
- IDEA
两种方式打包后都会在 target 目录下生成 hero-springboot-demo.jar,可以在命令行中启动。
原文链接:https://blog.csdn.net/youyacoder/article/details/126305576