Maven实战04_使用Archetype生成项目骨架

在上一章中的HelloWorld中,我们的项目遵循了一些Maven项目的约定

  • 在项目的根目录中放置pom.xml
  • 在src/main/java目录中放置项目的主代码
  • 在src/test/java目录中放置项目的测试代码

我们称以上这些基本的目录结构和pom.xml文件内容为项目的骨架。项目的骨架是固定的,这样的好处就是为了避免重复造轮子。

项目骨架的生成:

mvn archetype:generate

运行结果图


image

备注:构架项目骨架可能会报以下错误: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将插件将会根据我们提供的信息创建项目骨架,如图所示:

image

可以看到,包含程序主目录,测试目录,以及刚才定义的包名,以及我们之前用到的输出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来快速生成项目骨架,达到快速开发的目的。

原文地址:https://www.cnblogs.com/homeword/p/7128701.html