SpringBoot多环境开发部署

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/myNameIssls/article/details/83757045

SpringBoot多环境开发部署

需求描述

实际的工作中,我们项目会有不同的环境,最基本的包括开发环境(dev)、测试环境(test)、预发布环境(uat)和生产环境(prod)。
如果我们项目中只有一套环境配置,每次部署环境,都需要修改配置文件,例如:数据库连接、日志路径、MQ服务等。在多种不同的配置下,这种方式极容易出错。

实现步骤

在项目src/main/resources目录下新增不同环境的配置文件,本文将配置测试和开发两种环境来实现。
为了便于测试,配置文件仅以容器端口为内容。

添加开发环境配置(application-dev.yml)

server:
  port: 7000

添加测试环境配置(application-test.yml)

server:
  port: 7200

添加默认配置文件(application.yml)

spring:
  profiles:
    active: dev

如果项目启动时,不指定具体的配置文件,系统默认加载application.yml文件。

测试

打包

通过mvn clean install对项目进行打包。

指定不同配置启动项目

打包成功后,进入target目录中,通过java -jar ****.jar --spring.profiles.active=dev这种方式来指定启动不同的配置。

  • 基于开发环境启动项目
 java -jar springboot-example/target/springboot-example-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

观察控制台日志

2018-11-05 21:07:04.735  INFO 1188 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-11-05 21:07:04.795  INFO 1188 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 7000 (http) with context path ''
2018-11-05 21:07:04.877  INFO 1188 --- [           main] c.t.s.e.SpringBootExampleApplication     : Started SpringBootExampleApplication in 3.01 seconds (JVM running for 3.522)

本次项目启动端口是7000,对应着application-dev.yml配置文件中的配置。

  • 基于测试环境启动项目
java -jar springboot-example/target/springboot-example-0.0.1-SNAPSHOT.jar --spring.profiles.active=test

观察控制台日志:

2018-11-05 21:11:19.429  INFO 1193 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-11-05 21:11:19.576  INFO 1193 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 7200 (http) with context path ''
2018-11-05 21:11:19.580  INFO 1193 --- [           main] c.t.s.e.SpringBootExampleApplication     : Started SpringBootExampleApplication in 2.91 seconds (JVM running for 3.388)

本次项目启动端口是7200,对应着application-test.yml配置文件中的配置。

参考链接:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

源代码地址:
https://github.com/myNameIssls/springboot-study/tree/master/springboot-example

SpringBoot 企业级应用实战

猜你喜欢

转载自blog.csdn.net/myNameIssls/article/details/83757045