Maven生命周期介绍

生命周期的概念与意义

在项目构建时通常会包含清理、编译、测试、打包、验证、部署,文档生成等步骤,maven 统一对其进行了整理抽像成三个生命周期 (lifecycle)及各自对应的多个阶段(phase)。这么做的意义是:

  1. 每个阶段都成为了一个扩展点,可以采用不同的方式来实现,提高了扩展性与灵活性。
  2. 规范统一了maven 的执行路径。

在执行项目构建阶段时可以采用jar方式构建也可以采用war包方式构建,提高了灵活性。我们可以通过命令 mvn ${phase name}直接触发指定阶段的执行。

maven三大生命周期与其对应的phase(阶段)

maven 总共包含三大生生命周期

  1. clean Lifecycle :清理生命周期,用于于清理项目
  2. default Lifecycle:默认生命周期,用于编译、打包、测试、部署等
  3. site Lifecycle 站点文档生成,用于构建站点文档
    Maven生命周期介绍

上图给出了默认的生命周期的流程图,我么可以看到,生命周期也是抽象的流程概念,具体的实现,则是由相应的jar实现。这就好比抽象类或者接口,仅仅定义标准,也体现了具体场景中的灵活性。

生命周期(lifecycle) 阶段(phase) 描述(describe)
clean Lifecycle pre-clean 预清理
clean 清理
post-clean 清理之后
default Lifecycle validate 验证
initialize 初始化
generate-sources
process-sources
generate-resources
process-resources
compile 编译
process-classes
generate-test-sources
process-test-sources
generate-test-resources
process-test-resources
test-compile 编译测试类
process-test-classes
test 执行测试
prepare-package 构建前准备
package 打包构建
pre-integration-test
integration-test
post-integration-test
verify 验证
install 上传到本地仓库
deploy 上传到远程仓库
site Lifecycle pre-site 准备构建站点
site 构建站点
post-site 构建站点之后
site-deploy 站点部署

三大生命周期可以相互独立执行,也可以合在一起执行。但lifecycle 中的phase 是有严格执行的顺序的,比如必须是先执行完compile 才能执行pakcage 动作,此外phase 还有执行逻辑存在,即当你执行一个phase 时,其前面的phase 会自动执行。

生命周期的phase组成了项目过建的完整过程,但这些过程具体由谁来实现呢?这就是插件,maven 的核心部分代码量其实很少,其大部分实现都是由插件来完成的。比如:test 阶段就是由 maven-surefire-plugin 实现。在pom.xml 中我们可以设置指定插件目标(gogal)与phase 绑定,当项目构建到达指定phase时 就会触发些插件gogal 的执行。 一个插件有时会实现多个phase,比如:maven-compiler-plugin插件分别实现了compile 和testCompile。

在我们的项目当中并没有配置 maven-compiler-plugin 插件,但当我们执行compile 阶段时一样能够执行编译操作,原因是maven 默认为指定阶段绑定了插件实现。

下表列举了各个阶段的默认绑定插件,数据来源于Maven官网
Clean Lifecycle Bindings

Phase plugin:goal
clean clean:clean

Default Lifecycle Bindings - Packaging ear

Phase plugin:goal
generate-resources ear:generate-application-xml
process-resources resources:resources
package ear:ear
install install:install
deploy deploy:deploy

Default Lifecycle Bindings - Packaging jar

Phase plugin:goal
process-resources resources:resources
compile compiler:compile
process-test-resources resources:testResources
test-compile compiler:testCompile
test surefire:test
package jar:jar
install install:install
deploy deploy:deploy

Default Lifecycle Bindings - Packaging maven-plugin

Phase plugin:goal
generate-resources plugin:descriptor
process-resources resources:resources
compile compiler:compile
process-test-resources resources:testResources
test-compile compiler:testCompile
test surefire:test

Site Lifecycle Bindings

Phase plugin:goal
site site:site
site-deploy site:deploy

从表格数据我们可以看出,package阶段绑定插件非常灵活,生成不同的类型包,如jar,war或者ear,对应的默认插件是不同的。