目录
3.1 编写POM
就像make的makefile,ant的build.xml一样,Maven项目的核心是pom.xml
3.2 编写主代码
项目主代码会打包到最终的构件中(如jar),测试代码不会。
在绝大多数情况下,项目主码放到src/main/java目录下,无须额外的配置,Maven会自动搜寻还目录找到项目主代码。一般来说,项目中java类的包都应该基于项目的groupId和artifactId。
package com.wangwenxuan.maven.hh;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
命令行进入项目目录,执行:mvn clean compile
clean删除target文件。compile将主代码编译到target/classes目录。
注意:是clean不是clear,真心错了800次,还找不出原因。
3.3 编写测试代码
Maven可以自动去下载junit-4.7.jar.自动访问中央长裤,下载需要的文件。
package com.wangwenxuan.maven.hh;
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 );
}
}
典型的单元测试:1.准备测试类和数据 2.执行要测试的行为 3.检查结果
在JUnit3中,所有要执行的测试test开头,JUnit四中,需要执行的测试方法都应该以@Test进行标注。
测试用例编写结束后可以调用Maven测试:mvn clean test.
由于历史原因,Maven的核心插件之一——compiler插件默认只支持编译Java1.3,因此需要Java1.3以上的功能时需要配置该插件使其支持Java5
3.4 打包和运行
pom中没有指定打包类型时默认jar类型。使用命令:mvn clean package打包。
maven会在打包之前执行编译,测试等操作。命令成功后在target/输出目录中出现jar包。如果想用就可以将jar包复制到其它项目的classpath中使用。但是,如何让其它Maven项目直接引用这个jar?可以将jar存到本地仓库中。
执行一个安装的步骤:mvn clean install
3.5 使用Archetype生成骨架
命令行:
运行mvn archetype:generate
跳出很多信息,挑选想要的骨架(默认quickstart),然后输入下面的信息;
这就成功建成一个maven项目了。
长这个亚子
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wangwenxuan.maven</groupId>
<artifactId>hh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hh</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.wangwenxuan.maven.hh.App</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3.6 m2eclipse简单使用
3.6.1 导入Maven项目
file-import
3.6.2 创建Maven项目
file-new-orther-Maven-MavenProject-默认选项-添基本信息-finish
3.6.3 运行mvn命令
问题:compile不好使。好像是eclipse运行在jre而不是jdk上的问题。