【SpringBoot专题】多环境配置及swagger
前言
在上一篇博客《【SpringBoot专题】快速体验 》中已经带领大家初步了解了SpringBoot,本篇博客将为大家介绍多环境配置、swagger等相关内容。
多环境配置分析
在实际开发中,我们可能会涉及到一些环境,比如local(本地开发环境),dev(部署到远程的开发环境),test(预发布环境),product(生产环境)。显然,不同的环境下,对应不同的配置信息,比如db/redis/mq等,甚至不同的环境下,程序需要做不同的处理。那么springboot项目是如何支持多环境配置的呢?
首先来说,springboot就是一个可执行程序,通过java -jar的方式启动的,那么我们需要在启动的时候,告诉springboot当前的profile(环境)是什么,即:
java -jar xxx.jar --spring.profiles.active=test
通过这个--spring.profiles.active=test就是在告诉springboot,我们设置的profile是test。
实际开发中常用的多环境配置方式

如果你设置了--spring.profiles.active=test,那么springboot会支持加载application-test.properties文件。如果我们通过分目录来存放不同环境的配置文件呢,那么这个时候,需要我们先获取profile。
获取当前profile的方式

java -jar xxx.jar --spring.profiles.active=test
说白了,字符串“--spring.profiles.active=test”会传递到入口类的main方法的String[] args中!
CommandUtils

我们从args进行遍历处理,如果找到profile,那么通过System.setProperty进行系统key/value的设置(这里的key为"profile"),这是为了保存profile,方便以后拿到。
注意到,如果不给profile,那么自动设置为dev。
看一下CommandUtils中具体的解析profile方法


到这里,我们就可以根据profile来加载该profile下的配置文件了,比如:

在上文中,我们已经System.setProperty进行设置,将当前环境信息设置到profile变量中,因此我们直接进行${profile}引用了。
我们来看看application.properties文件内容:

假设我们想以test环境部署应用:


验证:


结果:


好了,到这里,多环境的配置就给大家介绍完毕了~
swagger
Swagger,英文翻译过来,就是有点拽,酷的意思,名符其实!
Swagger同springboot集成很简单,是一个很强大的api框架,不仅提供了在线文档的查阅(好似java doc),还提供了在线的http测试(好似postman等),简单帅气~
如何集成呢?