第3章 一切基于pom

第3章 一切基于pom

本章介绍了maven的核心pom.xml作用,详细描述了maven坐标变量。

3.1 什么是pom.xml

POM是项目对象模型(Project Object Model)的简称,它是Maven项目中的文件,使用XML表示,名称叫做pom.xml。maven项目中,除了一堆代码文件和跟项目有关的依赖文件外,还会包含一个pom.xml配置文件,这个文件配置了maven打包、编译、版本、路径等等的信息。其实,maven项目可以什么都没有,甚至没有代码,但是必须包含pom.xml文件。

3.2 maven坐标

maven坐标为各种构件引入了秩序,任何一个构件都必须明确定义自己的坐标,一组maven坐标包含:groupIdartifactIdversionpackagingclassifier

坐标值 介绍
groupId 定义当前maven项目隶属的实际项目,一个实际项目会有一个或多个maven项目。例如:springframework这一实际项目,包含多个maven项目,如spring-core、spring-aop、spring-beans、spring-webmvc等等。
artifactId 定义一个实际项目中的maven项目(模块),建议使用实际项目为前缀,例如org.hibernate。
version 定义maven项目当前的版本。
packaging 定义maven项目的打包方式。一般有jar、war、pom等。
classifier 定义maven在相同版本下针对不同的环境或者jdk使用的jar。

3.3 pom.xml基本介绍

3.3.1 基础标签

基础标签描述了项目的坐标和其他信息。

1
2
3
4
5
6
7
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx</groupId>
<artifactId>xxx_api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>xxx_api Maven Webapp</name>
<url>http://maven.apache.org</url>

3.3.2 继承标签

继承标签描述了父项目的坐标和路径

1
2
3
4
5
6
<parent>
<groupId>com.crm</groupId>
<artifactId>crm-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../crm-parent/pom.xml</relativePath>
</parent>

3.3.3 聚合标签

聚合标签描述了需要管理的子项目的路径

1
2
3
4
5
<modules>
<module>../crm-dao</module>
<module>../crm-service</module>
<module>../crm-web</module>
</modules>

3.3.4 依赖标签

1
2
3
4
5
6
7
8
<dependencies>
<dependency>
<groupId> javax.servlet </groupId>
<artifactId>jstl/artifactId>
<version>1.2</version>
</dependency>
……
</dependencies>

3.3.5 构建标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<build>
<finalName>crm-web </finalName>
<resources>
<resource>
<directory>${basedir}/src/${env}/resources</directory>
</resource>
</resources>
<outputDirectory>${basedir}/src/main/webapp/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warName>xxxxxx</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>

resources:描述工程中资源的位置。

outputDirectory:项目输出路径,默认情况下,项目的编译class是放在${basedir}/target下。

plugin:插件标签,描述项目工程需要的插件和插件的配置。

configuration:插件的一些配置信息。

3.3.6 maven隐式变量

${basedir}项目根目录
${project.build.directory} 构建目录,缺省为target
${project.build.outputDirectory}构建过程输出目录,缺省为target/classes
${project.build.finalName}产出物名称,缺省为${project.artifactId}-${project.version}
${project.packaging} 打包类型,缺省为jar
${project.xxx}当前pom文件的任意节点的内容