Maven入門教程

Fundebug發表於2019-01-08

GitHub倉庫:Fundebug/maven-tutorial

Maven簡介

Maven是Java專案構建工具,可以用於管理Java依賴,還可以用於編譯、打包以及釋出Java專案,類似於JavaScript生態系統中的NPM。

Maven的命令列工具為mvn,其常用命令如下表所示:

| 命令 | 說明 |
| ———– | ———————–|
| mvn compile | 編譯Java原始碼 |
| mvn package | 打包Java專案 |
| mvn deploy | 將Java專案釋出到Maven倉庫 |
| mvn clean | 刪除構建目錄 |

Maven的配置檔案為pom.xml,這個檔案有個很嚇人的學術名字Project Object Model,但是怎麼看它都只是個普通的配置檔案,與NPM中的package.json沒啥本質區別。

Maven的中央倉庫為Maven Repository,這裡可以找到各種Java依賴,例如我們Fundebug的異常監控外掛fundebug-javafundebug-spring

安裝Maven

在MacBook上使用brew安裝很方便

brew install maven

我安裝的是maven版本3.5.4

mvn -version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-18T02:33:14+08:00)
Maven home: /usr/local/Cellar/maven/3.5.4/libexec
Java version: 1.8.0_192, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.2", arch: "x86_64", family: "mac"

示例程式碼

本文示例程式碼都在GitHub倉庫Fundebug/maven-tutorial

使用tree命令可以檢視專案的目錄結構:

tree -v
.
├── pom.xml
└── src
    └── main
        └── java
            └── com
                └── fundebug
                    └── Hello.java

pom.xml為Maven配置檔案,位於專案的根目錄。

Hello.java為Java原始碼,位於src/main/java/com/fundebug目錄中。根據Maven對目錄結構的要求,Java原始碼必須位於src/main/java目錄。

Hello.java

package com.fundebug;

import org.json.JSONObject;

public class Hello {
        public static void main(String[] args) {
                JSONObject tomJsonObj = new JSONObject();
                tomJsonObj.put("name", "Fundebug");
                tomJsonObj.put("url", "https://www.fundebug.com");
                System.out.println(tomJsonObj.toString(4));
        }
}

Hello.java非常簡單,定義了一個JSON物件,然後把它列印出來了。

package定義的包名為com.fundebug,需要與所在的目錄結構相吻合,因此Hello.java位於src/main/java/com/fundebug目錄中,而不是src/main/java/目錄中。

程式碼依賴於第三方模組json,因此需要在pom.xml配置dependency:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <!-- 座標 -->
        <groupId>com.fundebug</groupId>
        <artifactId>hello</artifactId>
        <version>1.0</version>
        <!-- 依賴 -->
        <dependencies>
                <!-- https://mvnrepository.com/artifact/org.json/json -->
                <dependency>
                        <groupId>org.json</groupId>
                        <artifactId>json</artifactId>
                        <version>20180813</version>
                </dependency>
        </dependencies>
</project>

pom.xml中,<project></project>為最外層的標籤;<modelVersion>4.0.0</modelVersion>定義了所使用的POM版本。這2個標籤基本上是不變的。

groupId、artifactId與version一起則定義了模組的座標(Coordinates),每個公共模組的座標應該是唯一的:

  • groupId:組織名稱,通常是把域名反過來,例如com.fundebug
  • artifactId:模組名稱,例如fundebug-java
  • version:模組版本,例如0.2.0

<dependencies></dependencies>定義了當前專案所依賴的模組:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>
</dependencies>

Maven可以根據<dependency></dependency>中定義的座標,自動下載所依賴的模組。在MacBook上,Maven將下載的模組快取在$HOME/.m2/目錄。

使用mvn打包

執行mvn package命令,即可將原始碼打包為.jar檔案:

mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.fundebug:hello >-------------------------
[INFO] Building hello 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/fundebug/Desktop/maven-tutorial/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /Users/fundebug/Desktop/maven-tutorial/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hello ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/fundebug/Desktop/maven-tutorial/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ hello ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ hello ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ hello ---
[INFO] Building jar: /Users/fundebug/Desktop/maven-tutorial/target/hello-1.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.789 s
[INFO] Finished at: 2019-01-05T15:23:02+08:00
[INFO] ------------------------------------------------------------------------

mvn package執行之後,專案中會新增一個tartget目錄,編譯的位元組碼檔案位於target/classes目錄,而jar包位於target/hello-1.0.jar

tree -v
.
├── pom.xml
├── src
│   └── main
│       └── java
│           └── com
│               └── fundebug
│                   └── Hello.java
└── target
    ├── classes
    │   └── com
    │       └── fundebug
    │           └── Hello.class
    ├── hello-1.0.jar

使用mvn執行

打包好的jar包,可以直接使用java命令執行時,注意需要指定所依賴的jar包。對於所依賴的jar包,Maven則會自動下載依賴,放在本地倉庫中。在MacBook上,Maven本地倉庫位於$HOME/.m2/目錄。

java -cp target/hello-1.0.jar:$HOME/.m2/repository/org/json/json/20180813/json-20180813.jar com.fundebug.Hello
{
    "name": "Fundebug",
    "url": "https://www.fundebug.com"
}

也可以使用mvn exec:java命令執行,不需要指定依賴的jar包,更加方便:

mvn exec:java -Dexec.mainClass="com.fundebug.Hello"
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.fundebug:hello >-------------------------
[INFO] Building hello 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ hello ---
{
    "name": "Fundebug",
    "url": "https://www.fundebug.com"
}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.837 s
[INFO] Finished at: 2019-01-05T15:33:57+08:00
[INFO] ------------------------------------------------------------------------

參考