一般情况下我们的项目需要配置多个环境,可以使用Git的分支管理,也可以使用Maven来管理。
POM文件
Pom文件在
</project>
前加入以下配置,开发环境,测试环境,生产环境。
<!--分别设置开发,测试,生产环境-->
<!--打包命令 mvn clean package -Dprofiles.active=pro --> <profiles>
<profile>
<id>dev</id>
<activation>
<!--默认激活配置-->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<environment>dev</environment>
</properties>
</profile>
<!-- 测试 -->
<profile>
<id>test</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<environment>test</environment>
</properties>
</profile>
<!-- 生产 -->
<profile>
<id>prod</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<environment>prod</environment>
</properties>
</profile>
</profiles>
yaml文件
配置application.yml,application-dev.yml,application-test.yml,application-prod.yml,分别配置对应的内容。
application.yml
配置激活环境的变量,注意里面的内容
environment
和pom
是需要对的上的。
spring:
profiles:
active: @environment@
各环境配置文件
application-dev.yml,application-test.yml,application-prod.yml 对title的内容配置不同的内容,便于后面验证
server:
port: 8080
demo:
title: 我是开发环境
启动程序验证
注意日志的第三行,展示了启动的环境是开发环境
The following 1 profile is active: "dev"
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.3.7)
2025-01-17T19:17:49.255+08:00 INFO 31648 --- [ main] com.liu.demo.DemoEnvApplication : Starting DemoEnvApplication using Java 17.0.13 with PID 31648 (/home/liu/IDEA/demo-env/target/classes started by liu in /home/liu/IDEA/demo-env)
2025-01-17T19:17:49.257+08:00 INFO 31648 --- [ main] com.liu.demo.DemoEnvApplication : The following 1 profile is active: "dev"
2025-01-17T19:17:49.737+08:00 INFO 31648 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http)
2025-01-17T19:17:49.745+08:00 INFO 31648 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2025-01-17T19:17:49.745+08:00 INFO 31648 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.34]
2025-01-17T19:17:49.772+08:00 INFO 31648 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2025-01-17T19:17:49.773+08:00 INFO 31648 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 491 ms
2025-01-17T19:17:49.980+08:00 INFO 31648 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
2025-01-17T19:17:49.987+08:00 INFO 31648 --- [ main] com.liu.demo.DemoEnvApplication : Started DemoEnvApplication in 1.002 seconds (process running for 1.45)
浏览请求接口http://127.0.0.1:8080/test/title
展示内容:我是开发环境
注意:这部分内容写了
controller
获取了配置文件的title
代码:demo-env.zip
评论区