理解 Maven 项目的“身份证”
POM(Project Object Model) 是 Maven 项目的核心配置文件,通常叫 pom.xml,用于描述:
pom.xml 的价值在于“可复现”。同一份 POM,在不同机器/不同同事手上,跑同一条命令得到一致产物。
<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.example</groupId>
<artifactId>demo-project</artifactId>
<version>1.0.0</version>
</project>其中这三个字段合在一起,就构成了项目在 Maven 世界里的「唯一坐标」:
groupId:通常对应公司/组织/域名反写,如 com.exampleartifactId:项目名,如 demo-projectversion:版本号,如 1.0.0以后别的项目如果想依赖这个模块,只要在 POM 中写上同样的 groupId / artifactId / version,Maven 就能从仓库中把它找到并下载下来。
企业项目通常会补齐:Java 版本、编码、版本统一管理、构建插件等。
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo-app</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.10.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>
</project>jar:最常见的 Java 应用/类库war:传统容器部署pom:父工程/聚合工程(多模块)把“经常变化/需要统一”的值抽成属性:Java 版本、编码、依赖/插件版本等。
<dependencies>:真正引入依赖(进入 classpath)<dependencyManagement>:只管理版本/范围(不自动引入)<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.2.1-jre</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>dependencyManagement 负责“定规则”,dependencies 负责“用规则”。
Maven 的能力大量来自插件。你至少要会 2 个排查命令:
# 看最终生效的 POM(含 parent/profile/default 绑定)
mvn help:effective-pom
# 查看插件有哪些 goal
mvn help:describe -Dplugin=org.apache.maven.plugins:maven-surefire-plugin -Ddetail用于切换构建差异:是否跳过测试、不同仓库、不同打包参数等。
<profiles>
<profile>
<id>dev</id>
<properties>
<skipTests>true</skipTests>
</properties>
</profile>
</profiles>mvn -Pdev packagepom.xmlgroupId、artifactId、version 并记录下来pom.xml(参考本章示例)mvn validate 验证 POM 是否合法groupId、artifactId、versionproperties、dependencies、dependencyManagement、build/plugins、profiles