Maven 構建 Java 專案

Maven 使用原型 archetype 插件創建專案。要創建一個簡單的 Java 應用,我們將使用 maven-archetype-quickstart 插件。

在下面的例子中,我們將在 C:\MVN 檔夾下創建一個基於 maven 的 java 應用專案。

命令格式如下:

mvn archetype:generate -DgroupId=com.companyname.bank -DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

參數說明:

  • -DgourpId: 組織名,公司網址的反寫 + 專案名稱
  • -DartifactId: 專案名-模組名
  • -DarchetypeArtifactId: 指定 ArchetypeId,maven-archetype-quickstart,創建一個簡單的 Java 應用
  • -DinteractiveMode: 是否使用交互模式

生成的檔夾結構如下:

各個檔夾說明:

檔夾結構 描述
consumerBanking 包含 src 檔夾和 pom.xml
src/main/java contains java 代碼檔在包結構下(com/companyName/bank)。
src/main/test contains 測試代碼檔在包結構下(com/companyName/bank)。
src/main/resources 包含了 圖片 / 屬性 檔(在上面的例子中,我們需要手動創建這個結構)。

C:\MVN\consumerBanking\src\main\java\com\companyname\bank 檔夾中,可以看到一個 App.java,代碼如下:

App.java

package com.companyname.bank; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }

打開 C:\MVN\consumerBanking\src\test\java\com\companyname\bank 檔夾,可以看到 Java 測試檔 AppTest.java。

AppTest.java

package com.companyname.bank; 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 ); } }

接下來的開發過程中我們只需要按照上面表格中提到的結構放置好,其他的事情 Maven 幫我們將會搞定。