maven的動態打包功能


對於maven而言,打包是其一個非常重要的功能,不僅僅是簡單的編譯打包的概念,其還通過各種插件支持各種靈活的打包策略。現舉一個例子講解如何動態實現一個web項目的打包:

需求:

      現需要對一個web項目打出不同的3個包,3個包除了有公共的jar和配置文件依賴外,還各自需要依賴不同的特定的jar和特定的配置文件,而且不同的war包名字最好是不同的。

實現:

      我們可以利用 maven的profile機制和maven-war-plugin插件來完成以上需求,所有需要配置和修改的只涉及項目的pom文件,首先我們在pom文件中加入profile,不同的profile引入特定的jar依賴和動態定義${env}變量

   

<profiles>
        <profile>
            <id>one</id>
            <properties>
                <env>one</env>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>com.xxx</groupId>
                    <artifactId>project-one</artifactId>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>two</id>
            <properties>
                <env>two</env>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>com.xxx</groupId>
                    <artifactId>project-two</artifactId>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>three</id>
            <properties>
                <env>three</env>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>com.xxx</groupId>
                    <artifactId>project-three</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

然后引入maven-war-plugin插件,實現打包時根據不同的${env}變量動態引入不同的資源文件,並動態設定打包的包名:

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>deploy/${env}</directory>
                            <targetPath>WEB-INF/classes</targetPath>
                            <filtering>true</filtering>
                        </resource>
                    </webResources>
                    <warName>project-${env}</warName>
                </configuration>
            </plugin>

然后在項目下使用  mvn clean install -DskipTests=true -P ${profile_id} 進行打包 ,${profile_id}指各個不同的profile的id


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM