关于java:Maven的porfile与SpringBoot的profile结合使用详解

4次阅读

共计 2237 个字符,预计需要花费 6 分钟才能阅读完成。

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 相结合应用

正文完
 0