SpringBoot拾级而上·多环境切换

在 src/main/resources 目录下有一个文件 application.properties 是 springboot 在运行中所需要的配置信息。
当我们在开发阶段,使用自己的机器开发,测试的时候需要用的测试服务器测试,上线时使用正式环境的服务器。
这三种环境需要的配置信息都不一样,当我们切换环境运行项目时,需要手动的修改多出配置信息,非常容易出错。
为了解决上述问题,springboot 提供多环境配置的机制,让开发者非常容易的根据需求而切换不同的配置环境。
在 src/main/resources 目录下创建三个配置文件:
application-dev.properties:用于开发环境
application-test.properties:用于测试环境
application-prod.properties:用于生产环境
我们可以在这个三个配置文件中设置不同的信息,application.properties 配置公共的信息。
在 application.properties 中配置:

spring.profiles.active=dev

表示激活 application-dev.properties 文件配置, springboot 会加载使用 application.properties 和 application-dev.properties 配置文件的信息。
同理,可将 spring.profiles.active 的值修改成 test 或 prod 达到切换环境的目的。
我们可以尝试一下,给application-dev.properties配置8081的端口

server.port=8081

给application-test.properties配置8082的端口

server.port=8082

启动工程,我们可以在日志中看到如下的信息

2018-07-21 21:36:05.648  INFO 35528 --- [           main] c.s.s.SpringbootWebApplication           : Starting SpringbootWebApplication on feiyongdeMacBook-Pro.local with PID 35528 (/Users/feiyong/code/spring_boot/springboot_web/out/production/springboot_web started by feiyong in /Users/feiyong/code/spring_boot/springboot_web)
2018-07-21 21:36:05.652  INFO 35528 --- [           main] c.s.s.SpringbootWebApplication           : The following profiles are active: dev
2018-07-21 21:36:05.716  INFO 35528 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@29176cc1: startup date [Sat Jul 21 21:36:05 CST 2018]; root of context hierarchy
2018-07-21 21:36:06.695  INFO 35528 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2018-07-21 21:36:06.720  INFO 35528 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]

你可能感兴趣的:(SpringBoot拾级而上·多环境切换)