<b>3.4打包和運作</b>
将項目進行編譯、測試之後,下一個重要步驟就是打包(package)。hello world的pom中沒有指定打包類型,使用預設打包類型jar。簡單地執行指令 mvn clean package 進行打包,可以看到如下輸出:…
tests run: 1, failures: 0, errors: 0, skipped:
[info] [jar:jar {execution: defaultjar}]
[info] building jar: d:\code\helloworld\target\helloworld1.0snapshot.jar
[info]
------------------------------------------------------------------------
[info] build successful
…類似地,maven會在打包之前執行編譯、測試等操作。這裡看到jar:jar任務負責打包,實際上就是jar插件的jar目标将項目主代碼打包成一個名為helloworld1.0snapshot.jar的檔案。該檔案也位于target/輸出目錄中,它是根據artifactversion.jar規則進行命名的,如有需要,還可以使用finalname來自定義該檔案的名稱,這裡暫且不展開,後面會詳細解釋。
至此,我們得到了項目的輸出,如果有需要的話,就可以複制這個jar檔案到其他項目的classpath中進而使用helloworld類。但是,如何才能讓其他的maven項目直接引用這個jar呢?還需要一個安裝的步驟,執行 mvn clean install:…
[info] building jar: d: \code\helloworld\target\helloworld1.0snapshot.jar
[info] [install:install {execution: defaultinstall}]
[info] installing d:\code\helloworld\target\helloworld1.0snapshot.jar to c:\users\juven\.m2\repository\com\juvenxu\mvnbook\helloworld\1.0snapshot\helloworld1.0snapshot.jar
…在打包之後,又執行了安裝任務install:install。從輸出可以看到該任務将項目輸出的jar安裝到了maven本地倉庫中,可以打開相應的檔案夾看到hello world項目的pom和jar。之前講述junit的pom及jar的下載下傳的時候,我們說隻有構件被下載下傳到本地倉庫後,才能由所有maven項目使用,這裡是同樣的道理,隻有将hello world的構件安裝到本地倉庫之後,其他maven項目才能使用它。
我們已經體驗了maven最主要的指令:mvn clean compile、mvn clean test、mvn clean package、mvn clean install。執行test之前是會先執行compile的,執行package之前是會先執行test的,而類似地,install之前會執行package。可以在任何一個maven項目中執行這些指令,而且我們已經清楚它們是用來做什麼的。
到目前為止,還沒有運作hello world項目,不要忘了helloworld類可是有一個main方法的。預設打包生成的jar是不能夠直接運作的,因為帶有main方法的類資訊不會添加到manifest中(打開jar檔案中的metainf/manifest.mf檔案,将無法看到mainclass一行)。為了生成可執行的jar檔案,需要借助mavenshadeplugin,配置該插件如下:<plugin>
<groupid>org.apache.maven.plugins</groupid>
<artifactid>mavenshadeplugin</artifactid>
<version>1.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.
manifestresourcetransformer">
<mainclass>com.juvenxu.mvnbook.helloworld.helloworld</mainclass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin> plugin元素在pom中的相對位置應該在<project><build><plugins>下面。我們配置了mainclass為com.juvenxu.mvnbook.helloworld.helloworld,項目在打包時會将該資訊放到manifest中。現在執行 mvn clean install,待建構完成之後打開target/目錄,可以看到helloworld1.0snapshot.jar和originalhelloworld1.0snapshot.jar,前者是帶有mainclass資訊的可運作jar,後者是原始的jar,打開helloworld1.0snapshot.jar的metainf/manifest.mf,可以看到它包含這樣一行資訊:mainclass: com.juvenxu.mvnbook.helloworld.helloworld現在,在項目根目錄中執行該jar檔案:d: \code\helloworld>javajar target\helloworld1.0snapshot.jar
hello maven控制台輸出為hello maven,這正是我們所期望的。
本小節介紹了hello world項目,側重點是maven而非java代碼本身,介紹了pom、maven項目結構以及如何編譯、測試、打包等。