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…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理