maven - YUHAO-ZX/StudyCollection GitHub Wiki

1.<profiles>-><profile>用于自定义多套配置,可以根据条件来激活,实现动态配置

  • <id>配置名称
  • <build>此标签下配置需要适配的配置信息

2.<build>用于工程构建过程中的配置,如:源文件目录,资源目录,编译插件等

  • <finalName>打包后的工程名称
  • <resources>-><resource>-><directory>定义资源位置
  • <resource>-><filtering>如果值为true表示用<filter>标签中对应文件的配置来替代配置文件中的placeHolder
  • <resource>-><includes>-><include>表示哪些文件(支持通配符)适用于此配置
  • <resource>-><excludes>-><exclude>表示哪些文件不适用于此配置
  • <plugins>-><plugin>指定插件

应用:使用profile,resource->filtering来实现多环境多套配置,然后用命令:maven package -P<profile中定义的环境id>

eg. 定义多套变量

<profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <filters>
                    <!-- <filter>src/main/resources/test/config.properties</filter> -->
                    <filter>src/main/resources/dev/config.properties</filter>
                </filters>
            </build>
            <properties>
                <env>devcd</env>
            </properties>
        </profile>
        <profile>
            <id>stage</id>
            <build>
                <filters>
                    <filter>src/main/resources/stage/config.properties</filter>
                </filters>
            </build>
            <properties>
                <env>STAG</env>
            </properties>
        </profile>
<profiles>

设置资源位置和变量替换方案<filtering>

<build>
        <finalName>show</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.xls.png</include>
                </includes>
                <excludes>
                    <exclude>eclipse-code-formatter.xml</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <excludes>
                    <exclude>eclipse-code-formatter.xml</exclude>
                </excludes>
            </resource>
        <resources>
</build>

打包

maven package -Pstage

其他:java代码获取当前环境地址

Thread.currentThread().getContextClassLoader().getResource("conf.properties").getPath()

这种用法,需要在src/main/resources 下定义conf.properties

然后写入:

PASSPORT_URL=${passport.url}
PASSPORT_KEY=${passport.key}
PASSPORT_RPC_HOST=${PASSPORT_RPC_HOST}
PASSPORT_RPC_PORT=${PASSPORT_RPC_PORT}

实现java获取当前环境地址

⚠️ **GitHub.com Fallback** ⚠️