profile--多环境配置
- 应用maven的profile性能,咱们能够实现多环境配置文件的动静切换;
但随着SpringBoot我的项目越来越火,越来越多人喜爱用SpringBoot的profile性能。然而用SpringBoot的profile性能时,个别咱们默认激活的profile必定是开发环境的profile。当咱们打成jar包后,如果在生产环境下运行,就须要在运行这个jar包的命令前面加个命令行参数来指定切换的profile。尽管这样很不便,然而容易遗记加这个参数。 - 咱们能够通过maven的profile性能和SpringBoot的profile性能联合应用。
成果为:当maven打包时通过profile指定配置为test环境的配置,那么咱们SpringBoot外面默认激活的就是test环境的配置。 这样咱们只须要打包时指定profile后,间接运行jar就能够,不须要在命令行加参数了。这个成果就和咱们一般web我的项目应用maven的profile的成果相似了。
一、思路
(1)通过maven的profile性能,在打包的时候,通过-P指定maven激活某个pofile,这个profile外面配置了一个参数activatedProperties,不同的profile外面的这个参数的值不同
(2)SpringBoot的application.properties文件外面spring.profiles.active填的值取下面maven的activatedProperties参数值。
这样能实现的成果为:
- 示例一:
maven打包命令为 mvn clean package -P test
那么application.properties外面的spring.profiles.active值就是maven中 id为test的profile的activatedProperties参数值 - 示例二:
maven打包命令为 mvn clean package -P product
那么application.properties外面的spring.profiles.active值就是maven中 id为product的profile的activatedProperties参数值
二、案例
(1)我的项目构造介绍
我的项目构造如下图所示,是个常见的SpringBoot我的项目构造,不同环境的propertis文件的后缀不同(见图中红框处)
(2)pom文件中配置maven的profile
maven的profile的配置见上面代码
留神:maven的profile中activatedProperties参数值须要和SpringBoot的不同环境Properties文件的后缀一样。
比方开发环境的Properties的文件名为application-dev.properties,那么maven中dev的profile外面的activatedProperties参数值就应该是dev
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <activatedProperties>dev</activatedProperties> </properties> </profile> <profile> <id>test</id> <activation> <os> <family>mac</family> </os> </activation> <properties> <activatedProperties>test</activatedProperties> </properties> </profile> <profile> <id>production</id> <properties> <activatedProperties>production</activatedProperties> </properties> </profile> </profiles>
(3)application.properties中的配置
在application.properties文件中配置SpringBoot默认激活的propertis文件。这时候spring.profiles.active取下面maven的profile外面配置的activatedProperties
的值,这个取值要用@符号来取。具体见上面代码
spring.profiles.active\=@activatedProperties@
(4)如何打包
打包时用 mvn clean package -P profile的id
如果不加-P参数,那么默认就是<activeByDefault>true</activeByDefault>所在的profile
(5)效果图
当咱们打包命令为mvn clean package -P production 时,解压后的jar包中application.properties配置文件中spring.profiles.active的值主动变成了production
三、小结
(1)该形式长处:打包后不须要通过命令行参数来切换不同环境的配置文件,把指定环境的这一步放到了maven打包的命令上
(2)该形式其实是利用了maven的profile性能和SpringBoot的profile相结合应用