maven profile动态选择配置文件

一、前言

  在maven的项目中如果想实现在不同环境加载不同配置文件(不同的数据库、日志、使用参数等配置),可以优先考虑使用配置profile的方式来实现

二、在maven的pom.xml文件中配置:

(1)pom中指定配置的id和配置信息

 <profiles>
        <profile>
            <!-- 本地开发环境 -->
            <id>dev</id>
            <properties>
                <profiles.active>dev</profiles.active>
            </properties>
            <activation>
                <!-- 设置默认激活这个配置 -->
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 发布环境 -->
            <id>prod</id>
            <properties>
                <profiles.active>prod</profiles.active>
            </properties>
        </profile>
        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
                <!--
                如果在properties或者yml中实用改变量使用@引用,
                比如server.port=@server.port@
                -->
                <server.port>8400</server.port>
            </properties>
        </profile>
    </profiles>

(2)在构建jar或者war包时候引用配置文件

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!--一定要设置成true.这样才会用对应env目录下的配置文件覆盖原来的-->
                <filtering>true</filtering>
                <excludes>
                    <exclude>application.properties</exclude>
                    <exclude>application-dev.properties</exclude>
                    <exclude>application-test.properties</exclude>
                    <exclude>application-prd.properties</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <!--一定要设置成true.这样才会用对应env目录下的配置文件覆盖原来的-->
                <filtering>true</filtering>
                <includes>
                    <include>application.properties</include>
                    <include>application-${profiles.active}.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

三、指定文件的启动方式:

1)默认的激活

  上面的profile配置中设置的默认的激活环境。如下面所示

<activeByDefault>true</activeByDefault> 

2)使用-P参数显示激活一个profile

  当我们在进行Maven操作时就可以使用-P参数显示的指定当前激活的是哪一个profile了。比如我们需要在对项目进行打包的时候使用id为dev的profile,我们就可以这样做:

mvn package –Pdev

   这里假设dev是在settings.xml中使用dev标记的处于激活状态的profile,那么当我们使用“-P !profile”的时候就表示在当前操作中该profile将不处于激活状态。

https://www.cnblogs.com/0201zcr/p/6262762.html

原文地址:https://www.cnblogs.com/niunafei/p/12633222.html