mvn compile 与 clean
compile 和 clean 是最常用的构建命令。
compile 命令
基本用法
Bash
mvn compile
执行阶段
Bash
validate → initialize → generate-sources → process-sources
→ generate-resources → process-resources → compile
输出位置
Bash
target/classes/
├── com/
│ └── example/
│ └── Main.class
│ └── Utils.class
└── application.properties
clean 命令
基本用法
XML
mvn clean
执行阶段
Bash
pre-clean → clean → post-clean
执行效果
Bash
删除 target 目录及其全部内容:
target/
├── classes/
├── test-classes/
├── generated-sources/
├── maven-status/
└── *.jar
组合命令
Bash
# 清理后重新编译
mvn clean compile
# 清理后打包
mvn clean package
# 清理后安装
mvn clean install
增量编译 vs 全量编译
增量编译
XML
仅编译变更的文件:
1. 检查源码修改时间
2. 对比 class 文件时间
3. 仅编译有变化的源码
全量编译
XML
clean compile 强制全量编译:
1. 删除所有 class 文件
2. 重新编译全部源码
选择策略
| 场景 | 命令 |
|---|---|
| 日常开发 | mvn compile(增量) |
| 发布构建 | mvn clean compile(全量) |
| 出现异常 | mvn clean compile(重建) |
| CI/CD 构建 | mvn clean package(全量) |
编译参数配置
text
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
<encoding>UTF-8</encoding>
<!-- 强制重新编译 -->
<forceJavacCompilerUse>true</forceJavacCompilerUse>
</configuration>
</plugin>
查看编译结果
text
# 查看编译日志
mvn compile -X
# 查看编译产物
ls target/classes
编译错误排查
常见错误
| 错误 | 原因 |
|---|---|
| 编码错误 | 源码编码与配置不一致 |
| 类找不到 | 依赖未引入 |
| 版本错误 | source/target 配置错误 |
排查方法
text
# 详细错误日志
mvn compile -e
# 显示编译详细信息
mvn compile -X
编译警告处理
查看警告
text
mvn compile -Xlint:unchecked
配置编译警告
text
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-Xlint:unchecked</arg>
<arg>-Xlint:deprecation</arg>
</compilerArgs>
</configuration>
</plugin>
clean 扩展配置
清理额外目录
text
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<filesets>
<fileset>
<directory>logs</directory>
<includes>
<include>**/*.log</include>
</includes>
</fileset>
</filesets>
</configuration>
</plugin>
要点总结
- mvn compile 编译源码到 target/classes
- mvn clean 删除 target 目录
- 日常开发用增量编译,发布用全量编译
- clean compile 确保完整重建
- 编译错误用 -e 和 -X 排查
- source/target 配置 Java 版本
📝 发现内容有误?点击此处直接编辑