Maven 標准目錄結構
好的目錄結構可以使開發人員更容易理解項目,為以后的維護工作也打下良好的基礎。Maven2根據業界公認的最佳目錄結構,為開發者提供了缺省的標准目錄模板。Maven2的標准目錄結構如下:

| src/main/java | Application/Library sources |
| src/main/resources | Application/Library resources |
| src/main/filters | Resource filter files |
| src/main/assembly | Assembly descriptors |
| src/main/config | Configuration files |
| src/main/scripts | Application/Library scripts |
| src/main/webapp | Web application sources |
| src/test/java | Test sources |
| src/test/resources | Test resources |
| src/test/filters | Test resource filter files |
| src/site | Site |
| LICENSE.txt | Project's license |
| NOTICE.txt | Notices and attributions required by libraries that the project depends on |
| README.txt | Project's readme |
使用目錄模板,可以使 pom.xml 更簡潔。因為 Maven2 已經根據缺省目錄,預定義了相關的動作,而無需人工的干預。以 resources 目錄為例:
- src/main/resources,負責管理項目主體的資源。在使用Maven2執行compile之后,這個目錄中的所有文件及子目錄,會復制到target/classes目錄中,為以后的打包提供了方便。
- src/test/resources,負責管理項目測試的資源。在使用Maven2執行test-compile之后,這個目錄中的所有文件及子目錄,會復制到target/test-classes目錄中,為后續的測試做好了准備。
這些動作在 Maven1 中,是需要在 maven.xml 中使用<preGoal>或<postGoal>來完成的。如今,完全不需要在pom.xml中指定就能夠自動完成。在src和test都使用resources,方便構建和測試,這種方式本就已是前人的經驗。通過使用Maven2,使這個經驗在開發團隊中得到普及。
創建標准目錄模板,可以通過如下命令:
mvn archetype:create -DgroupId=com.codeline.commons -DartifactId=codelineCommons
groupId和artifactId的含義與Maven1中的含義一樣,參數artifactId的值會作為項目根目錄的名字。除了建立相應的目錄之外,Maven2還會創建缺省的pom.xml。
Maven2也考慮到:不同類型的項目需要擁有不同的目錄結構。如創建web項目,可以使用命令:
mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-webapp -DarchetypeArtifactId=maven-archetype-webapp
Maven 生命周期
Maven生命周期已經在另一篇博客中介紹過了(http://www.cnblogs.com/haippy/archive/2012/07/04/2576453.html),這里引用IBM developerworks 的文章再一次討論Maven 的生命周期。
在Maven2中有了明確的生命周期概念,而且都提供與之對應的命令,使得項目構建更加清晰明了。主要的生命周期階段:
- validate,驗證工程是否正確,所有需要的資源是否可用。
- compile,編譯項目的源代碼。
- test-compile,編譯項目測試代碼。
- test,使用已編譯的測試代碼,測試已編譯的源代碼。
- package,已發布的格式,如jar,將已編譯的源代碼打包。
- integration-test,在集成測試可以運行的環境中處理和發布包。
- verify,運行任何檢查,驗證包是否有效且達到質量標准。
- install,把包安裝在本地的repository中,可以被其他工程作為依賴來使用
- deploy,在整合或者發布環境下執行,將最終版本的包拷貝到遠程的repository,使得其他的開發者或者工程可以共享。
- generate-sources,產生應用需要的任何額外的源代碼,如xdoclet。
如果要執行項目編譯,那么直接輸入:mvn compile即可,對於其他的階段可以類推。階段之間是存在依賴關系(dependency)的,如test依賴test-compile。在執行mvn test時,會先運行mvn test-compile,然后才是mvn test。
