maven-assembly-plugin把java工程打包成為一個可執行檔jar包__maven

來源:互聯網
上載者:User

用java寫了一個小工具,使用maven java 工程。寫完後,想打包成一個可執行檔jar包。
使用maven的外掛程式maven-assembly-plugin

pom.xml裡添加

<build>      <plugins>        <plugin>          <artifactId>maven-assembly-plugin</artifactId>          <configuration>            <archive>              <manifest>                <mainClass>org.kuan.wang.App</mainClass>              </manifest>            </archive>            <descriptorRefs>              <descriptorRef>jar-with-dependencies</descriptorRef>            </descriptorRefs>          </configuration>        </plugin>      </plugins>    </build>

執行命令:

mvn clean compile assembly:single

在target檔案夾裡產生MavenTestApp-1.0-SNAPSHOT-jar-with-dependencies.jar
這個jar包便是可執行檔jar了,用命令java -jar path\jarfile便可以執行。
注意:compile必須再assembly:single之前,要不然你工程的代碼(class檔案)就不會被打包進去

assembly:single是maven的goal.
通常情況下,這個goal要綁定到maven build 的phase裡,這樣它就可以自動執行。mvn package是用來打包jar包的。只是jar包不可執行。
在以上的pom檔案裡加<executions>

<plugin>  <artifactId>maven-assembly-plugin</artifactId>  <configuration>    <archive>      <manifest>        <mainClass>org.kuan.wang.App</mainClass>      </manifest>    </archive>    <descriptorRefs>      <descriptorRef>jar-with-dependencies</descriptorRef>    </descriptorRefs>  </configuration>  <executions>    <execution>      <id>make-assembly</id> <!-- this is used for inheritance merges -->      <phase>package</phase> <!-- bind to the packaging phase -->      <goals>        <goal>single</goal>      </goals>    </execution>  </executions></plugin>

這樣的話直接運行以下命令就行了。

mvn clean package

另外有幾點要注意。
1. 必須要有

<archive>     <manifest>          <mainClass>org.kuan.wang.App</mainClass>     </manifest></archive>

否則會報錯
no main manifest attribute, in target\MavenTestApp-1.0-SNAPSHOT-jar-with-dependencies.jar
<mainClass>是你自己工程的入口。
2. 使用mvn clean compile assembly:single,只產生一個jar包,名字裡有jar-with-dependencies,可執行。
使用mvn package產生兩個jar包,名字裡有jar-with-dependencies的jar是可執行檔。
3. 如果使用<goal>assembly</goal>
用命令mvn assembly:assembly會產生兩個jar包。跟使用了mvn package一樣
無需再像命令assembly:single一樣前面必須加compile.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.