在软件开发过程中,需要进行多个环境的测试和部署,包括开发环境、测试环境、预发布环境和生产环境。不同的环境需要不同的配置,例如数据库地址、Redis地址、服务器端口等。如果每次打包时都需要手动修改配置文件,那将会非常繁琐和容易出错。
为了解决这个问题,常用的做法是使用不同的配置文件来存储不同环境的配置信息。这些配置文件包含了环境特定的设置,例如数据库连接字符串、API密钥、调试标志等。在打包时,可以根据需要选择对应环境的配置文件,并将其打包到部署包中。
多数项目构建工具或框架都支持这种方式。例如,Maven中使用不同的配置文件和打包命令来实现多环境部署;Spring Boot中可以使用profile来指定不同的环境。
使用多环境配置可以有效地提高部署的效率和减少错误率。同时,也使得项目的开发和部署更加灵活和可控。
Spring Boot中多环境配置文件名需要满足application-{profile}.properties或者application-{profile}.yml的格式,其中{profile}对应你的环境标识
properties语法
application.properties #主配置文件
application-dev.properties #开发环境的配置
application-test.properties #测试环境的配置
application-uat.properties #uat境的配置
application-prod.properties #生产环境的配置
yml 语法
application.yml #主配置文件
application-dev.yml #开发环境的配置
application-test.yml #测试环境的配置
application-uat.yml #uat境的配置
application-prod.yml #生产环境的配置
每个环境的properties 设置branch分支的值
-
默认dev
-
application.properties:
#默认使用dev的配置 spring.profiles.active=dev -
application.yml:
spring: profiles: active: dev
-
-
dev环境 端口8080
-
application.properties:
server.port=8080 branch=dev -
application.yml:
server: port: 8080 branch: dev
-
-
test环境 端口8081
-
application.properties:
server.port=8081 branch=test -
application.yml:
server: port: 8081 branch: test
-
-
uat环境 端口8082
-
application.properties:
server.port=8082 branch=uat -
application.yml:
server: port: 8082 branch: uat
-
-
prod 环境 端口 8083
-
application.properties:
server.port=80823 branch=prod -
application.yml:
server: port: 8083 branch: prod
-
在HelloController读取brand值
package com.mingsl.lesson.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${branch}")
private String branch;
@GetMapping("/hello")
public String hello(){
return "Hello Word";
}
@GetMapping("/branch")
public String getBranch(){
return " Spring Boot Current branch "+branch;
}
}
打包
#第一步打开Idea 编译器最底部的Terminal终端
mvn clean package
运行
运行dev环境
java -jar F:\lesson\backend\code\mingsl-project\mingsl-admin-api\target\mingsl-admin-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
运行test环境
java -jar F:\lesson\backend\code\mingsl-project\mingsl-admin-api\target\mingsl-admin-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=test
运行uat环境
java -jar F:\lesson\backend\code\mingsl-project\mingsl-admin-api\target\mingsl-admin-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=uat
运行prod环境
java -jar F:\lesson\backend\code\mingsl-project\mingsl-admin-api\target\mingsl-admin-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod