Maven的porfile与SpringBoot的profile结合使用详解

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、思路

(1)经过maven的profile功能,在打包的时候,经过-P指定maven激活某个pofile,这个profile里面配置了一个参数activatedProperties,不一样的profile里面的这个参数的值不一样 web

(2)SpringBoot的application.properties文件里面spring.profiles.active填的值取上面maven的activatedProperties参数值。spring

这样能实现的效果为:app

  • 示例一:
    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参数值

2、案例

(1)项目结构介绍

项目结构以下图所示,是个常见的SpringBoot项目结构,不一样环境的propertis文件的后缀不一样(见图中红框处)maven

(2)pom文件中配置maven的profile

maven的profile的配置见下面代码spa

注意:maven的profile中activatedProperties参数值须要和SpringBoot的不一样环境Properties文件的后缀同样。命令行

好比开发环境的Properties的文件名为application-dev.properties,那么maven中dev的profile里面的activatedProperties参数值就应该是dev3d

<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的值,这个取值要用@符号来取。具体见下面代码code

spring.profiles.active\=@activatedProperties@
(4)如何打包

打包时用 mvn clean package -P profile的idblog

若是不加-P参数,那么默认就是<activeByDefault>true</activeByDefault>所在的profile开发

(5)效果图

当咱们打包命令为mvn clean package -P production 时,解压后的jar包中application.properties配置文件中spring.profiles.active的值自动变成了production

3、小结

(1)该方式优势:打包后不须要经过命令行参数来切换不一样环境的配置文件,把指定环境的这一步放到了maven打包的命令上

(2)该方式实际上是利用了maven的profile功能和SpringBoot的profile相结合使用

相关文章
相关标签/搜索