天天看點

Maven實戰. 3.2編寫主代碼

<b>3.2編寫主代碼</b>

項目主代碼和測試代碼不同,項目的主代碼會被打包到最終的構件中(如jar),而測試代碼隻在運作測試時用到,不會被打包。預設情況下,maven假設項目主代碼位于src/main/java目錄,我們遵循maven的約定,建立該目錄,然後在該目錄下建立檔案com/juvenxu/mvnbook/helloworld/helloworld.java,其内容如代碼清單3-2所示:代碼清單3-2hello world的主代碼

package com.juvenxu.mvnbook.helloworld;

public class helloworld

{

public string sayhello()

return "hello maven";

}

public static void main(string[] args)

system.out.print(

new helloworld().sayhello()

);

這是一個簡單的java類,它有一個sayhello()方法,傳回一個string。同時這個類還帶有一個main方法,建立一個helloworld執行個體,調用sayhello()方法,并将結果輸出到控制台。

關于該java代碼有兩點需要注意。首先,在絕大多數情況下,應該把項目主代碼放到src/main/java/目錄下(遵循maven的約定),而無須額外的配置,maven會自動搜尋該目錄找到項目主代碼。其次,該java類的包名是com.juvenxu.mvnbook.helloworld,這與之前在pom中定義的groupid和artifactid相吻合。一般來說,項目中java類的包都應該基于項目的groupid和artifactid,這樣更加清晰,更加符合邏輯,也友善搜尋構件或者java類。

代碼編寫完畢後,使用maven進行編譯,在項目根目錄下運作指令 mvn clean compile會得到如下輸出:[info] scanning for projects…

[info]

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

[info] building maven hello world project

[info]tasksegment: [clean, compile]

[info] [clean:clean {execution: defaultclean}]

[info] deleting directory d:\code\helloworld\target

[info] [resources:resources {execution:

defaultresources}]

[info] skip non existing resourcedirectory d:

\code\helloworld\src\main\resources

[info] [compiler:compile {execution: defaultcompile}]

[info] compiling 1 source file to d: \code\helloworld\target\classes

[info] build successful

[info] total time: 1 second

[info] finished at: fri oct 09 02:08:09 cst

2009

[info] final memory: 9m/16m

------------------------------------------------------------------------clean告訴maven清理輸出目錄target/,compile告訴maven編譯項目主代碼,從輸出中看到maven首先執行了clean:clean任務,删除target/目錄。預設情況下,maven建構的所有輸出都在target/目錄中;接着執行resources:resources任務(未定義項目資源,暫且略過);最後執行compiler:compile任務,将項目主代碼編譯至target/classes目錄(編譯好的類為com/juvenxu/mvnbook/helloworld/helloworld.class)。

上文提到的clean:clean、resources:resources和compiler:compile對應了一些maven插件及插件目标,比如clean:clean是clean插件的clean目标,compiler:compile是compiler插件的compile目标。後文會詳細講述maven插件及其編寫方法。

至此,maven在沒有任何額外的配置的情況下就執行了項目的清理和編譯任務。接下來,編寫一些單元測試代碼并讓maven執行自動化測試。