1. 程式人生 > >Maven學習總結系列三:Maven入門

Maven學習總結系列三:Maven入門

1.編寫POM

Maven專案的核心就是pom.xml,POM(Project Object Model,專案物件模型)定義了專案的基本資訊,用於描述專案如何構建,宣告專案依賴,等等。

還記得我們第一章遇到的問題嗎?

在開發的過程中,我們需要到各個網站上下載第三方的JAR包,隨著專案的慢慢增大,JAR包會變得越來越多,可能出現包之間的版本衝突,專案變得臃腫等問題。

然後Maven提出了座標來為每一個artifact給定唯一的標識。從此artifact從亂混中解放出來,整個JAR包世界變得有秩序,有標準。

同時Maven自動識別artifact之間的依賴關係,從而自動下載依賴的JAR包,不再需要我們去網站上額外下載。

它還會檢測一些未在專案上使用的JAR包,這樣方便我們清除不需要包,對專案做一個瘦身。

而實現這些功能,Maven是通過一個pom.xml檔案配置來實現的。

1.1 一個簡單的pom.xml配置

首先,我們得先為自己定義一個座標

-------------------------------------------------------------------------------------------

<projectxmlns="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/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.juvenxu.mvnbook</groupId>

  <artifactId>hello-world</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <name>MavenHello World Project</name>

  <dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

<scope>test</scope>

</dependency>

  </dependencies>

</project>

-------------------------------------------------------------------------------------------

相關資訊說明:

modelVersion:指定了當前POM的模型版本,對於Maven3來說,它只能是4.0.0

groupId, artifactId 和version:三個元素定義了一個專案的基本座標。 在Maven的世界,任何的Jar,pom 或war都是以基於這些基本的座標進行區分的。

groupId, 定義了專案屬於哪個組,這個組往往和專案所在的組織或公司存在關聯。

如:googlecode建立一個名為myapp的專案,則groupId為com.googlecode.myapp

artifactId, 定義了當前Maven專案在組中唯一的ID。

如:這個專案是myapp的一個模組,service層,則為myapp-service,為了區分,識別這個service是哪個組的,會使用  組名-模組  這樣的命名方式,這裡 組名為 myapp,模組名 service,所以artifactId為myapp-service

version:指定專案的當前版本。

name:宣告一個對於使用者更為友好的專案名稱。

1.2 編寫主程式碼

專案主程式碼會被打包到最終的構件中(如jar),而測試程式碼只在執行測試時用到,不會被打包。

Maven的約定目錄結構:

 

其中:

專案主程式碼:src/main/java

專案主資源:src/main/resources

測試程式碼:src/test/java

測試資源:src/test/resources

helloWorld.java

----------------------------------------------------

packagecom.juvenxu.mvnbook.helloWorld;

publicclass HelloWorld{

public String sayHello(){

return "Hello World!";

}

public static void main(String []args){

System.out.println(new HelloWorld().sayHello());

}

}

----------------------------------------------------

目錄結構如下:

E:\maven\workspace\HelloWorld>tree

FolderPATH listing

Volumeserial number is 000000E0 C4F5:2D3F

E:.

└─src

    ├─main

    │ └─java

    │     └─com

    │         └─juvenxu

    │              └─mvnbook

    │                  └─helloWorld

    └─test

        └─java

            └─com

                └─java1234

                    └─helloWorld

使用Maven進行編譯

clean:告訴Maven清理輸出目錄target/

compile:告訴Maven編譯專案主程式碼。

E:\maven\workspace\HelloWorld>mvn clean compile

[INFO]Scanning for projects...

[INFO]

[INFO]------------------------------------------------------------------------

[INFO]Building Maven Hello World Project 0.0.1-SNAPSHOT

[INFO]------------------------------------------------------------------------

[INFO]

[INFO]--- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---

[INFO]

[INFO]--- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\main\resources

[INFO]

[INFO]--- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO] Compiling 1 source file toE:\maven\workspace\HelloWorld\target\classes

[INFO]------------------------------------------------------------------------

[INFO]BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO]Total time: 4.476 s

[INFO]Finished at: 2017-10-25T22:49:40+08:00

[INFO]Final Memory: 13M/243M

[INFO]------------------------------------------------------------------------

編譯後目錄結構,target產生編譯程式碼:

E:\maven\workspace\HelloWorld>tree

FolderPATH listing

Volumeserial number is 00000027 C4F5:2D3F

E:.

├─src

│  ├─main

│  │ └─java

│  │     └─com

│  │         └─juvenxu

│  │             └─mvnbook

│  │                  └─helloWorld

│  └─test

│      └─java

│          └─com

└─target

    ├─classes

    │ └─com

    │     └─juvenxu

    │         └─mvnbook

    │              └─helloWorld

    └─maven-status

        └─maven-compiler-plugin

            └─compile

                └─default-compile

清理target目錄

E:\maven\workspace\HelloWorld>mvn clean

[INFO]Scanning for projects...

[INFO]

[INFO]------------------------------------------------------------------------

[INFO]Building Maven Hello World Project 0.0.1-SNAPSHOT

[INFO]------------------------------------------------------------------------

[INFO]

[INFO]--- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---

[INFO] Deleting E:\maven\workspace\HelloWorld\target

[INFO]------------------------------------------------------------------------

[INFO]BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO]Total time: 0.226 s

[INFO]Finished at: 2017-10-25T22:52:41+08:00

[INFO]Final Memory: 7M/243M

[INFO]------------------------------------------------------------------------

E:\maven\workspace\HelloWorld>tree

FolderPATH listing

Volumeserial number is 000000E0 C4F5:2D3F

E:.

└─src

    ├─main

    │ └─java

    │     └─com

    │         └─juvenxu

    │              └─mvnbook

    │                  └─helloWorld

    └─test

        └─java

            └─com

1.3 編寫測試程式碼

Maven為了使專案結構保持清晰,主程式碼與測試程式碼分別位於獨立的目錄中。

Test the code:

1.Createtest folder

2.Set theJunit jar into pom.xml

3.codethe test source code

為了測試,我們需要在pom.xml新增一個Junit artifact,好讓maven幫我們下載這個jar包。

pom.xml

---------------------------------------------------------------------------------------------------------------

<projectxmlns="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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

 <modelVersion>4.0.0</modelVersion>

 <groupId>com.juvenxu.mvnbook</groupId>

 <artifactId>hello-world</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <name>Maven Hello WorldProject</name>

  <dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

<scope>test</scope>

</dependency>

  </dependencies>

</project>

-------------------------------------------------------------------------------------------------------

一個典型的單元測試包含三個步驟:

a.準備測試類及資料。

b.執行要測試的行為;

c.檢查結果。

在Junit中,約定所有需要執行測試的方法都以test開頭。

Create test class

在src/test/java下建立測式用例

HelloWorldTest.java

-----------------------------------------------------------------------

packagecom.juvenxu.mvnbook.helloWorld;

importorg.junit.Test;

publicclass HelloWorldTest{

@Test

public void testSayHello(){

HelloWorld helloWorld=new HelloWorld();

String result=helloWorld.sayHello();

System.out.println(result);

}

}

----------------------------------------------------------------------

Note:the method name must begin with 'test'.

Eg.testSayHello()

呼叫Maven執行測試: mvn clearn test

E:\maven\workspace\HelloWorld>mvn clean test

[INFO]Scanning for projects...

[INFO]

[INFO]------------------------------------------------------------------------

[INFO]Building Maven Hello World Project 0.0.1-SNAPSHOT

[INFO]------------------------------------------------------------------------

[INFO]

[INFO] --- maven-clean-plugin:2.5:clean (default-clean)@ hello-world ---

[INFO]

[INFO] --- maven-resources-plugin:2.6:resources(default-resources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\main\resources

[INFO]

[INFO] --- maven-compiler-plugin:3.1:compile(default-compile) @ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO] Compiling 1 source file toE:\maven\workspace\HelloWorld\target\classes

[INFO]

[INFO] --- maven-resources-plugin:2.6:testResources(default-testResources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\test\resources

[INFO]

[INFO] --- maven-compiler-plugin:3.1:testCompile(default-testCompile) @ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO] Compiling 1 source file toE:\maven\workspace\HelloWorld\target\test-classes

[INFO]

[INFO] --- maven-surefire-plugin:2.12.4:test(default-test) @ hello-world ---

[INFO] Surefire report directory:E:\maven\workspace\HelloWorld\target\surefire-reports

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

Runningcom.juvenxu.mvnbook.helloWorld.HelloWorldTest

Hello World!

Testsrun: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.058 sec

Results :

Testsrun: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]------------------------------------------------------------------------

[INFO]BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO]Total time: 3.524 s

[INFO]Finished at: 2017-10-25T23:07:12+08:00

[INFO]Final Memory: 15M/210M

[INFO]------------------------------------------------------------------------

由上面的輸出我們可以看到,在執行test之前,它會先自動執行

專案主資源處理,主程式碼編譯,測試資源處理,測試程式碼編譯等工作,這是Maven生命週期的一個特性,執行生命週期中某個命令時,必須要先執行這個生命週期中它之前的命令。

mvn clean test will execute command:

--- maven-clean-plugin:2.5:clean

--- maven-resources-plugin:2.6:resources

--- maven-compiler-plugin:3.1:compile

--- maven-resources-plugin:2.6:testResources

--- maven-compiler-plugin:3.1:testCompile

--- maven-surefire-plugin:2.12.4:test

現在專案結構如下:

E:\maven\workspace\HelloWorld>tree /F

FolderPATH listing

Volumeserial number is 000000ED C4F5:2D3F

E:.

│  pom.xml

├─src

│  ├─main

│  │ └─java

│  │     └─com

│  │         └─juvenxu

│  │             └─mvnbook

│  │                  └─helloWorld

│  │                          HelloWorld.java

│  │

│  └─test

│      └─java

│          └─com

│              └─juvenxu

│                  └─mvnbook

│                      └─helloWorld

│                            HelloWorldTest.java

└─target

    ├─classes

    │ └─com

    │     └─juvenxu

    │         └─mvnbook

    │              └─helloWorld

    │                      HelloWorld.class

    │

    ├─maven-status

    │ └─maven-compiler-plugin

    │      ├─compile

    │     │  └─default-compile

    │     │          createdFiles.lst

    │     │          inputFiles.lst

    │     │

    │     └─testCompile

    │         └─default-testCompile

    │                  createdFiles.lst

    │                  inputFiles.lst

    │

    ├─surefire-reports

    │     com.juvenxu.mvnbook.helloWorld.HelloWorldTest.txt

    │     TEST-com.juvenxu.mvnbook.helloWorld.HelloWorldTest.xml

    └─test-classes

        └─com

            └─juvenxu

                └─mvnbook

                    └─helloWorld

                            HelloWorldTest.class

3.4 打包和執行 mvn clean package

將專案進行編譯,測試之後,下一個重要步驟就是打包(package)。

當POM檔案中沒的指定打包型別時,maven的預設打包型別是jar.

E:\maven\workspace\HelloWorld>mvn clean package

[INFO]Scanning for projects...

[INFO]

[INFO]------------------------------------------------------------------------

[INFO]Building Maven Hello World Project 0.0.1-SNAPSHOT

[INFO]------------------------------------------------------------------------

[INFO]

[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @hello-world ---

[INFO]Deleting E:\maven\workspace\HelloWorld\target

[INFO]

[INFO] --- maven-resources-plugin:2.6:resources(default-resources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\main\resources

[INFO]

[INFO] --- maven-compiler-plugin:3.1:compile (default-compile)@ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO]Compiling 1 source file to E:\maven\workspace\HelloWorld\target\classes

[INFO]

[INFO] --- maven-resources-plugin:2.6:testResources(default-testResources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\test\resources

[INFO]

[INFO] --- maven-compiler-plugin:3.1:testCompile(default-testCompile) @ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO]Compiling 1 source file to E:\maven\workspace\HelloWorld\target\test-classes

[INFO]

[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @hello-world ---

[INFO]Surefire report directory:E:\maven\workspace\HelloWorld\target\surefire-reports

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

Runningcom.juvenxu.mvnbook.helloWorld.HelloWorldTest

HelloWorld!

Testsrun: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.059 sec

Results :

Testsrun: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]

[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ hello-world ---

[INFO]Building jar: E:\maven\workspace\HelloWorld\target\hello-world-0.0.1-SNAPSHOT.jar

[INFO]------------------------------------------------------------------------

[INFO]BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO]Total time: 7.572 s

[INFO]Finished at: 2017-10-26T20:13:23+08:00

[INFO]Final Memory: 15M/200M

[INFO]------------------------------------------------------------------------

執行pacakge後,maven會把專案主程式碼打包成一個名為hello-world-0.0.1-SNAPSHOT.jar的檔案。

該檔案也位於target輸出目錄中。

命名規則:

artifact-version.jar

如果這個名不適用,可以用finalName來重新定義輸出名稱。

輸出結果如下:

E:\maven\workspace\HelloWorld>tree/F

FolderPATH listing

Volumeserial number is 0000004C C4F5:2D3F

E:.

│  pom.xml

├─src

│  ├─main

│  │ └─java

│  │     └─com

│  │         └─juvenxu

│  │             └─mvnbook

│  │                  └─helloWorld

│  │                          HelloWorld.java

│  │

│  └─test

│      └─java

│          └─com

│              └─juvenxu

│                  └─mvnbook

│                      └─helloWorld

│                             HelloWorldTest.java

└─target

    │  hello-world-0.0.1-SNAPSHOT.jar

    ├─classes

    │ └─com

    │     └─juvenxu

    │         └─mvnbook

    │              └─helloWorld

    │                      HelloWorld.class

    │

    ├─maven-archiver

    │     pom.properties

    │

    ├─maven-status

    │ └─maven-compiler-plugin

    │      ├─compile

    │     │  └─default-compile

    │     │          createdFiles.lst

    │     │          inputFiles.lst

    │     │

    │     └─testCompile

    │         └─default-testCompile

    │                  createdFiles.lst

    │                  inputFiles.lst

    │

    ├─surefire-reports

    │     com.juvenxu.mvnbook.helloWorld.HelloWorldTest.txt

    │     TEST-com.juvenxu.mvnbook.helloWorld.HelloWorldTest.xml

   │

    └─test-classes

        └─com

            └─juvenxu

                └─mvnbook

                    └─helloWorld

                           HelloWorldTest.class

Note: Now, we cancopy this jar package to the classpath of other project to use it.

Another way, we can install it to the local repository instead ofcopy the jar manually.

安裝JAR包到本地倉庫 mvn clearn install

安裝JAR到本地倉庫後,其它專案可以使用這個JAR包:

Let other Project to use this jar package , we needinstall this jar to local repository.

E:\maven\workspace\HelloWorld>mvn clean install

[INFO]Scanning for projects...

[INFO]

[INFO]------------------------------------------------------------------------

[INFO]Building Maven Hello World Project 0.0.1-SNAPSHOT

[INFO]------------------------------------------------------------------------

[INFO]

[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---

[INFO]Deleting E:\maven\workspace\HelloWorld\target

[INFO]

[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\main\resources

[INFO]

[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO]Compiling 1 source file to E:\maven\workspace\HelloWorld\target\classes

[INFO]

[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hello-world ---

[WARNING]Using platform encoding (GBK actually) to copy filtered resources, i.e. buildis platform dependent!

[INFO]skip non existing resourceDirectoryE:\maven\workspace\HelloWorld\src\test\resources

[INFO]

[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ hello-world ---

[INFO]Changes detected - recompiling the module!

[WARNING]File encoding has not been set, using platform encoding GBK, i.e. build isplatform dependent!

[INFO]Compiling 1 source file to E:\maven\workspace\HelloWorld\target\test-classes

[INFO]

[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ hello-world ---

[INFO]Surefire report directory:E:\maven\workspace\HelloWorld\target\surefire-reports

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

Runningcom.juvenxu.mvnbook.helloWorld.HelloWorldTest

HelloWorld!

Testsrun: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.067 sec

Results :

Testsrun: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]

[INFO] --- maven-jar-plugin:2.4:jar(default-jar) @ hello-world ---

[INFO]Building jar: E:\maven\workspace\HelloWorld\target\hello-world-0.0.1-SNAPSHOT.jar

[INFO]

[INFO] --- maven-install-plugin:2.4:install (default-install) @ hello-world ---

[INFO]Installing E:\maven\workspace\HelloWorld\target\hello-world-0.0.1-SNAPSHOT.jartoE:\maven\repository\com\juvenxu\mvnbook\hello-world\0.0.1-SNAPSHOT\hello-world-0.0.1-SNAPSHOT.jar

[INFO]Installing E:\maven\workspace\HelloWorld\pom.xml to E:\maven\repository\com\juvenxu\mvnbook\hello-world\0.0.1-SNAPSHOT\hello-world-0.0.1-SNAPSHOT.pom

[INFO]------------------------------------------------------------------------

[INFO]BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO]Total time: 2.945 s

[INFO]Finished at: 2017-10-26T20:21:36+08:00

[INFO]Final Memory: 16M/212M

[INFO]------------------------------------------------------------------------

 

到這裡為止,我們按照Maven的對於結構目錄的約定來建立 專案主程式碼,測試程式碼的目錄及 主程式碼,測試程式碼。並而執行了 從 clean, compile , test, package, install 的生命週期中的操作。

問題:有沒有覺得手工建立這些目錄很累,有沒有一種方式,可以快速建立一個Maven約定的專案骨構?省得我們一個個手工建?

專案骨架:指maven約定的基本目錄結構和pom.xml檔案內容。

方案:maven archetype, 可以快速的建立專案的骨架。

之所有我們一個個的手工建,是為了讓我們在建立過程中體會預設約定背後的思想及體驗整個過程。

Using ArcheType to build the artifact of prject

The following is the artifact of project:

The question is: how to build them quickly?

E:\maven\workspace>mvn archetype:generate

[INFO] Scanning forprojects...

1959: remote ->us.fatehi:schemacrawler-archetype-maven-project (-)

1960: remote ->us.fatehi:schemacrawler-archetype-plugin-command (-)

1961: remote ->us.fatehi:schemacrawler-archetype-plugin-dbconnector (-)

1962: remote ->us.fatehi:schemacrawler-archetype-plugin-lint (-)

Choose a number orapply filter (format: [groupId:]artifactId, case sensitive contains): 1057:1057

Chooseorg.apache.maven.archetypes:maven-archetype-quickstart version:

1: 1.0-alpha-1

2: 1.0-alpha-2

3: 1.0-alpha-3

4: 1.0-alpha-4

5: 1.0

6: 1.1

Choosea number: 6:6

Define value forproperty 'groupId': com.juvenxu.mvnbook

Define value forproperty 'artifactId': say-hello

Define value forproperty 'version' 1.0-SNAPSHOT: :

Define value forproperty 'package' com.juvenxu.mvnbook: : com.juvenxu.mvnbook.sayHello

Confirm properties configuration:

groupId:com.juvenxu.mvnbook

artifactId:say-hello

version:1.0-SNAPSHOT

package:com.juvenxu.mvnbook.sayHello

 Y: : y

[INFO]----------------------------------------------------------------------------

[INFO] Usingfollowing parameters for creating project from Old (1.x) Archetype:maven-archetype-quickstart:1.1

[INFO]----------------------------------------------------------------------------

[INFO] Parameter:basedir, Value: E:\maven\workspace

[INFO] Parameter:package, Value: com.juvenxu.mvnbook.sayHello

[INFO] Parameter:groupId, Value: com.juvenxu.mvnbook

[INFO] Parameter:artifactId, Value: say-hello

[INFO] Parameter:packageName, Value: com.juvenxu.mvnbook.sayHello

[INFO] Parameter:version, Value: 1.0-SNAPSHOT

[INFO] projectcreated from Old (1.x) Archetype in dir: E:\maven\workspace\say-hello

[INFO]------------------------------------------------------------------------

[INFO] BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO] Total time:10:10 min

[INFO] Finished at:2017-10-26T21:16:25+08:00

[INFO] Final Memory:14M/153M

[INFO]------------------------------------------------------------------------

我們可以看到,maven已經自動幫我們建立了maven專案的骨架出來。

E:\maven\workspace>cdsay-hello

E:\maven\workspace\say-hello>tree/F

Folder PATH listing

Volume serial numberis 00000063 C4F5:2D3F

E:.

│  pom.xml

└─src

    ├─main

    │ └─java

    │     └─com

    │         └─juvenxu

    │              └─mvnbook

    │                  └─sayHello

    │                          App.java

    │

    └─test

        └─java

            └─com

                └─juvenxu

                    └─mvnbook

                        └─sayHello

                                AppTest.java

同時,pom.xml也生成了預設的內容

pom.xml

------------------------------------------------------------------------------------------------------------------------

<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 <modelVersion>4.0.0</modelVersion>

  <groupId>com.juvenxu.mvnbook</groupId>

  <artifactId>say-hello</artifactId>

  <version>1.0-SNAPSHOT</version>

  <packaging>jar</packaging>

  <name>say-hello</name>

 <url>http://maven.apache.org</url>

  <properties>

   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

  <dependencies>

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

</project>

------------------------------------------------------------------------------------------------------------------------

說明:Archetype可以幫助我們迅速地構建起專案的骨架,在前面的例子中,我們完全可以在Archetype生成的骨架的基礎上開發Hello World專案以節省大量時間。

3.6 Create maven project in eclipse

Import amaven project which has just be build name say-Hello

 

 


1.6.2 Create a new maven project

在eclipse中建立一個Maven專案也很簡單,File ->New -> Other

 

 

 

由於eclipse實際上是在使用maven-archetype-plugin外掛建立專案。因此這個過程與上面使用archetype建立專案骨架是一樣的。

 

點選“Finish”後,系統自動建立骨構,如下:

 

專案主程式碼:

App.java

----------------------------------------------------------

packagecn.ss.maven.test.helloWorld;

/**

 * Hello world!

 *

 */

public class App

{

    public static void main( String[] args )

    {

        System.out.println( "HelloWorld!" );

    }

}

----------------------------------------------------------

pom.xml

----------------------------------------------------------

<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 <modelVersion>4.0.0</modelVersion>

 <groupId>cn.ss.maven.test</groupId>

 <artifactId>helloWorld</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>

  <name>helloWorld</name>

 <url>http://maven.apache.org</url>

  <properties>

   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

  <dependencies>

    <dependency>

  <groupId>junit</groupId>

     <artifactId>junit</artifactId>

      <version>3.8.1</version>

      <scope>test</scope>

    </dependency>

  </dependencies>

</project>

----------------------------------------------------------

在Eclipse中,我們使用pom.xml-->Run As操作來執行maven命令。

You canexecute maven command in this way:

 

Or youcan build the customized Maven command such as mvnclean test by Maven build or press Alt + Shift + X,M

 

Click "Run" button: system will execute the command wehave defined 'clean test'

It like execute 'mvn clean test'

The result as below:

[INFO] Scanning forprojects...

[INFO]                                                                        

[INFO]------------------------------------------------------------------------

[INFO] BuildinghelloWorld 0.0.1-SNAPSHOT

[INFO]------------------------------------------------------------------------

[INFO]

[INFO] ---maven-clean-plugin:2.5:clean (default-clean) @ helloWorld ---

[INFO] DeletingD:\Workspaces\eclipse-jee-oxygen_x86_64\helloWorld\target

[INFO]

[INFO] ---maven-resources-plugin:2.6:resources (default-resources) @ helloWorld ---

[INFO] Using 'UTF-8'encoding to copy filtered resources.

[INFO] skip nonexisting resourceDirectoryD:\Workspaces\eclipse-jee-oxygen_x86_64\helloWorld\src\main\resources

[INFO]

[INFO] ---maven-compiler-plugin:3.1:compile (default-compile) @ helloWorld ---

[INFO] Changesdetected - recompiling the module!

[INFO] Compiling 1source file toD:\Workspaces\eclipse-jee-oxygen_x86_64\helloWorld\target\classes

[INFO]

[INFO] ---maven-resources-plugin:2.6:testResources (default-testResources) @ helloWorld---

[INFO] Using 'UTF-8'encoding to copy filtered resources.

[INFO] skip nonexisting resourceDirectoryD:\Workspaces\eclipse-jee-oxygen_x86_64\helloWorld\src\test\resources

[INFO]

[INFO] ---maven-compiler-plugin:3.1:testCompile (default-testCompile) @ helloWorld ---

[INFO] Changesdetected - recompiling the module!

[INFO] Compiling 1source file toD:\Workspaces\eclipse-jee-oxygen_x86_64\helloWorld\target\test-classes

[INFO]

[INFO] ---maven-surefire-plugin:2.12.4:test (default-test) @ helloWorld ---

[INFO] Surefirereport directory:D:\Workspaces\eclipse-jee-oxygen_x86_64\helloWorld\target\surefire-reports

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

Runningcn.ss.maven.test.helloWorld.AppTest

Tests run: 1,Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec

Results :

Tests run: 1,Failures: 0, Errors: 0, Skipped: 0

[INFO]------------------------------------------------------------------------

[INFO] BUILD SUCCESS

[INFO]------------------------------------------------------------------------

[INFO] Total time:6.752 s

[INFO] Finished at:2017-10-26T21:30:56+08:00

[INFO] Final Memory:19M/214M

[INFO]------------------------------------------------------------------------

小結:本章詳細的敘述瞭如何手工建立符合maven骨構的Hello World專案,解釋了POM的基本內容,Maven專案的基本結構及構建專案基本的Maven命令。

如何使用Archetype快速的建立maven骨架及如何在Eclipse建立maven專案。