乐趣区

Maven 教程

1. 介绍
构建(build)一个项目包括:下载依赖,编译源代码,执行单元测试,以及打包编译后的源代码等一系列子任务。手工的执行这些任务是一项非常繁琐,且容易出错的事情。Maven 封装了这些子任务,并提供给用户执行这些子任务的命令。简而言之,Maven 是 Java 项目的一个管理和构建(build)工具。
2. 项目对象模型(Project Object Model)
项目对象模型(以下简称 POM)是 Maven 的基本组成单元,它是位于项目主目录下的一个 xml 文件(pom.xml),Maven 使用 pom.xml 文件中的信息来构建(build)项目。
一个简单的 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/maven-v4_0_0.xsd”>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-app</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
//…
</plugin>
</plugins>
</build>
</project>
本小结将介绍 pom.xml 中常用的一些元素。
2.1 项目标识符(Project Identifiers)

groupId – 创建项目的公司或者组织的名称

artifactId – 项目的名称

version – 项目的版本号

packaging – 项目的打包方式(jar/war/pom)

GAV (groupId:artifactId:version) 是 Maven 项目的唯一表示符。packaging 决定 Maven 生成包的类型,默认值是 jar。
2.2 依赖(dependencies)
pom.xml 文件通过元素 <dependency> 来声明外部依赖,例如:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
声明项目依赖 3.8.1 版本的 junit。默认情况下,Maven 将在构建项目的时候从 Maven 的中央仓库(Central Repository)下载依赖到本地仓库(${USER_HOME/.m2/repository/})。不过用户也可以通过元素 <repository> 来声明备选仓库(alternate repository)。
2.3 属性(Properties)
可以像在 Java 等编程语言中定义变量一样,在 pom.xml 文件中定义属性,这样就可以达到一处定义,多处使用的目的,使用和维护起来也更加容易。
pom.xml 中通过元素 <properties> 定义属性,通过占位符 ${property_name} 使用属性。如下:
<properties>
<spring.version>4.3.5.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
如果在将来需要升级 spring-core 和 spring-context 的版本,那时将只需要修改属性 spring.version 的值。
2.4 构建(build)
未完待续 ……
参考

https://www.baeldung.com/maven
https://maven.apache.org/guid…
https://maven.apache.org/guid…

退出移动版