最近因为项目要求,原先的项目只有开发环境的项目配置,后来不利于线上测试,因而,最近对于SpringBoot这部分多环境配置在网上查找了相关资料,并实现了配置,因而为了防止遗忘,特在此进行总结。在此,感谢如下博主的文章:http://www.javashuo.com/article/p-xjzsarrh-nn.html;http://www.javashuo.com/article/p-kffplvoa-nm.html。java
好啦,废话很少说,开启正文(好像很正式的样子呢。。。。。。)spring
下面以一个小案例,进行说明。springboot
如图所示,下图是案例中的三个配置文件,其中,服务器
application.yml是启动服务时,服务器会自动加载的配置文件,app
application-dev.yml 表示的是开发环境的配置文件,maven
application-prod.yml 表示的是生产环境的配置文件,ide
对于,dev和prod这两个文件在启动服务时,服务器不会自动加载,那么在不一样的环境中时怎么调用不一样的文件的呢?测试
主要有如下两种方式:idea
具体操做步骤以下:spa
1> 进入到项目目录下,先用mvn install命令对项目进行打包,执行完此步骤后,会在项目对应的target目录下生成该项目对应的jar包
2> 进入target目录,执行命令:java -jar 生成的jar包 --spring.profiles.active=prod
经过此命令以后,项目就会调用application-prod.yml配置文件,即以生产环境的配置要求启动服务。同理,如果开发环境,只需将prod改成dev便可。
具体步骤以下:
1> application.yml中将spring.profiles.active的值改为spring.profiles.active=@activatedProperties@,这里的@activatedProperties@是一个变量对应pom文件里的环境配置。
下面为pom文件的配置<profiles> <profile>
<id>dev</id> <properties> <!-- 环境标识,须要与配置文件的名称相对应 --> <activatedProperties>dev</activatedProperties> </properties> <activation> <!-- 默认环境 --> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <!-- 测试环境 --> <activatedProperties>test</activatedProperties> </properties> </profile> <profile> <id>prod</id> <properties> <!-- 生产环境 --> <activatedProperties>prod</activatedProperties> </properties> </profile> </profiles>
注意:<activatedProperties>dev</activatedProperties>中的dev与配置文件名称application-dev.yml要一致
activatedProperties名称对应application.properties配置文件中的spring.profiles.active=@activatedProperties@
当maven打包时会用pom文件里<activatedProperties>dev</activatedProperties>中的值替换掉application.properties配置文件中的@activatedProperties@
2> 执行Maven打包命令mvn clean package,观察控制台日志
已经构建成功,刷新一下项目,target会生成SpringbootMybatis-0.0.1-SNAPSHOT.jar包。
1.=='@' that cannot start any token. (Do not use @ for indentation)
在本地启动该项目时有时候会报以下错误
found character '@' that cannot start any token. (Do not use @ for indentation) in 'reader', line 4, column 11: name: @profiles.active@
意思是识别不了@profiles.active@这个变量,这是由于这个变量没有被替换成咱们须要的参数,如test,prod等,因此在本地启动时要加上参数启动,这样springboot会自动替换掉这个变量。
做者使用的是idea,因此启动springboot时在右上Edit Configurations-->Active Profiles 增长一个参数,参数值为你须要运行的环境名称,如test
注:上述中的application-dev.yml、application-prod.myl等只是演示案例中名字,并不是全部项目都是如此,还请各位以实际项目为主。