在 Maven 里通过指定 application.properties 打包 SpringBoot 项目

发表于 2020-06-10 15:28:29
阅读 127

介绍

介绍

我们的项目在不同的环境里的配置参数是不一样的,开发环境的参数,生产环境的参数都是不同的

不能每次变换环境都要重新改一遍参数吧?

今天我们就来学习如何通过 profiles 来实现不同的环境调用不同的 application.properties 配置文件

教程

建立多个 application.properties 配置文件

里面根据不同环境设置不同的参数

假设我们这里有 application-develop.properties 和 application-product.properties 两个配置文件

application-develop.properties
application-product.properties

在 pom.xml 里的 project 节点下面设置 profiles

一个 develop,一个 product,其中 develop 是默认激活的

每个 profile 设置不同的 app-ppts 参数

<profiles>
    <profile>
        <id>develop</id>
        <properties>
            <env>develop</env>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>product</id>
        <properties>
            <env>product</env>
        </properties>
    </profile>
</profiles>

在 pom.xml 里的 project -> build 节点下面设置 resources

先排除所有 properties 文件

再根据环境加载指定的 properties 文件

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <excludes>
            <exclude>application*.properties</exclude>
        </excludes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
            <include>application.properties</include>
            <include>application-${env}.properties</include>
        </includes>
    </resource>
</resources>

在 application.properties 里增加一行

指定 spring.profiles.active 为 @env@,也就是上面的配置文件的变量

spring.profiles.active=@env@

通过 mvn 打包

我们使用 -P 参数指定开发环境

mvn clean package -Dmaven.test.skip=true -Pdevelop

总结

  • 如果通过 -P 指定的 profile 是不存在的,则 mvn 会调用默认的进行导入