pom介绍
pom.xml(project object model项目对象模型)定义了项目基本的信息。用于描述项目如何构建,声明项目依赖等。现在通过hello world项目编写最简单的pom.xml
1.步骤
1.创建hello-world文件夹,打开文件夹新建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">
<!--groupId,artifactId,version定义了一个项目基本的坐标,任何jar,pom,war都是基于这些基本坐标进行区分,
如公司叫mycom下的一个myapp项目,那么groupId就应该是com.mycom.mypp,artifactId定义Maven项目在组中唯一的id,-->
<modelVersion>4.0.0</modelVersion>
<groupId>com.cityeve</groupId>
<artifactId>hello-world</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Maven Hello World project</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
代码中添加了dependencies元素,该元素下可包含多个dependency元素以声明项目的依赖。这里添加一个gourpId是junit, artifactId是junit,version是4.7.这三个参数是任何一个maven项目最基本的坐标,通过这三个参数就可以去maven远程仓库下载junit 4.7的包,scope为依赖范围,依赖范围为test说明该依赖只对测试有效。
2.编写主代码
遵循maven的约定,项目的主代码在src/main/java目录,在该目录创建自己的包路径,我的E:\hello-world\src\main\java\com\
cityeve\helloworld
package com.cityeve.helloworld;
public class HelloWorld {
public String sayHello(){
return "Hello Maven";
}
public static void main(String[] args) {
System.out.println(new HelloWorld().sayHello());
}
}
cmd命令下跳转到项目根目录下(E:\hello-world)下执行mvn clean compile正确执行在根目录会自动创建target文件夹,下面target/classes目录里生成编译好的HelloWorld.class文件。
3.编写测试代码
测试路径E:\hello-world\src\test\java\com\cityeve\helloworld,(maven中默认主代码目录src/main/java和默认测试代码
目录src/test/java)
package com.cityeve.helloworld;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class HelloWorldTest {
@Test
public void testSayHello(){
HelloWorld helloworld=new HelloWorld();
String result=helloworld.sayHello();
assertEquals("Hello Maven",result);
}
}
cmd命令下跳转到项目根目录下(
E:\hello-world)下执行mvn clean test ,测试成功
如果失败了,可能是这个错
4.打包
同样在根目录下执行mvn clean package ,理论上在target目录下会看到根据artifact-version.jar规则命名生成的一个jar文件
通过配置pom.xml的<packaging>jar/war</packaging>生成war等文件
同样在根目录执行 mvn clean install
可以看到在默认的本地仓库中安装了当前的jar包,只有将Hello World的构件安装到本地仓库后,其它maven项目才能使用它。
使用Archetype生成项目骨架
以上的目录结构和pom.xml文件称为项目的骨架,maven 提供了archetype帮助我们快速勾勒项目骨架,Maven3可以通过命令mvn archetype:generate ,输出停止时回车确认使用默认编号的骨架,然后要求填写groupId,artifactId,version,package 我这分别填写为com.cityeve hello-taray 1.0-SNAPSHOT com.cityeve.helloworld输入Y生成
会在E盘根目录生成一个hello-taray的文件夹,结构和上面手动创建的一样。可以开发自己的archetype一劳永逸。
eclipse导入maven项目
eclipse导入我们刚才写的helloworld项目:
选择刚才的hello-world项目,点击finish导入成功,一个标准的maven项目结构产生了:
可以看到junit4.7位置是本地的默认仓库,结构是默认的maven项目src main java和src test java