在上一章中的HelloWorld中,我們的項目遵循了一些Maven項目的約定
- 在項目的根目錄中放置pom.xml
- 在src/main/java目錄中放置項目的主代碼
- 在src/test/java目錄中放置項目的測試代碼
我們稱以上這些基本的目錄結構和pom.xml文件內容爲項目的骨架。項目的骨架是固定的,這樣的好處就是爲了避免重複造輪子。
項目骨架的生成:
mvn archetype:generate
運行結果圖
備註:構架項目骨架可能會報以下錯誤:Unable to add module to the current project as it is not of packaging type 'pom'
紅框下面的第一行是Archetype編號,在Maven中,每一個Archetype前面都會對應有一個編號,同時命令行會提示一個默認的編號,這裏是1268,其對應的Archetype爲maven-archetype-quickstart,直接回車以選擇該Archetype,緊接着Maven會提示出入要創建項目的groupId、artifactId、version、以及包名packpage,輸入後並確認:Y
Archetype將插件將會根據我們提供的信息創建項目骨架,如圖所示:
可以看到,包含程序主目錄,測試目錄,以及剛纔定義的包名,以及我們之前用到的輸出HelloMaven的類及其測試類。
代碼清單:
App.java
package com.soulprayer.maven.maven_study; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
AppTest.java
import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
在這裏僅僅是看到一個最簡單的Archetype,如果有很多項目擁有類似的自定義項目結構以及配置文件,則完全可以一勞永逸地開發自己的Archetype,然後在這些項目中使用自定義的Archetype來快速生成項目骨架,達到快速開發的目的。