03-Maven构建生命周期简介

文章目录

Introduction to the Build Lifecycle

Table Of Contents

Build Lifecycle Basics

Maven is based around【基于】 the central concept of a build lifecycle. What this means is that【这意味着】 the process for building and distributing a particular artifact (project) is clearly defined.

For the person building a project, this means that【这意味着】 it is only necessary to【只需要】 learn a small set of【一小套】 commands to build any Maven project, and the POM will ensure they get the results they desired.

There are three built-in【内置的】 build lifecycles: default, clean and site. The default lifecycle handles your project deployment, the clean lifecycle handles project cleaning, while the site lifecycle handles the creation of your project’s web site.

A Build Lifecycle is Made Up of Phases

Each of these build lifecycles is defined by a different list of build phases【阶段】, wherein【其中】 a build phase represents a stage【阶段】 in the lifecycle.

For example, the default lifecycle comprises of【由…组成;包括】 the following phases (for a complete list of the lifecycle phases, refer to the Lifecycle Reference):

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met【满足质量标准】
  • install - install the package into the local repository【本地仓库】, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository【远程仓库】 for sharing with other developers and projects.

These lifecycle phases (plus【外加】 the other lifecycle phases not shown here) are executed sequentially【按顺序执行】 to complete the default lifecycle.

Given【鉴于;考虑到】 the lifecycle phases above,

this means that when the default lifecycle【默认生命周期】 is used,

1、Maven will first validate the project,

2、then will try to compile the sources,

3、run those against the tests,

4、package the binaries (e.g. jar),

5、run integration tests against that package, verify the integration tests,

6、install the verified package to the local repository,

7、then deploy the installed package to a remote repository.

[top].

Usual Command Line Calls

You should select the phase that matches your outcome【匹配您的结果】. If you want your jar, run package. If you want to run the unit tests, run test.

If you are uncertain what you want, the preferred【更好的;首选的】 phase to call is

mvn verify

This command executes each default lifecycle phase in order【按顺序】 (validate, compile, package, etc.), before executing verify. You only need to call the last build phase to be executed, in this case, verify【既然这样;在这种情况下…推荐调用verify】. In most cases the effect is the same as package【在大多数情况下,结果和调用package一样】. However, in case there are integration-tests, these will be executed as well. And during the verify phase some additional checks can be done, e.g. if your code written according to the predefined checkstyle rules【预定义的检查样式规则?】.

In a build environment, use the following call to cleanly build and deploy artifacts into the shared repository.

mvn clean deploy

The same command can be used in a multi-module scenario【多模块方案/工程】 (i.e.【也就是;即 - 用于解释让人难以理解的术语】 a project with one or more subprojects). Maven traverses into【遍历】 every subproject and executes clean, then executes deploy (including all of the prior【前面提到的】 build phase steps).

[top].

I.e.和e.g.究竟啥意思?这些拉丁文缩写你分清了吗?

A Build Phase is Made Up of Plugin Goals

However, even though a build phase is responsible for a specific step in the build lifecycle, the manner in which it carries out those responsibilities may vary. And this is done by declaring the plugin goals bound to those build phases.

翻译一下:即使一个构建阶段负责构建生命周期的一个具体步骤,然而它执行这些职责的方式可能会有所不同这是通过声明绑定到这些构建阶段的构建目标来完成的

A plugin goal represents a specific task (finer than【比…精细;细于】 a build phase) which contributes to【有助于】 the building and managing of a project. It may be bound to zero or more build phases. A goal not bound to【未绑定到】 any build phase could be executed outside of the build lifecycle【执行于构建生命周期之外】 by direct invocation【直接调用】. The order of execution depends on the order in which the goal(s) and the build phase(s) are invoked. For example, consider the command below. The clean and package arguments are build phases, while the dependency:copy-dependencies is a goal (of a plugin).

mvn clean dependency:copy-dependencies package

If this were to be【将要】 executed, the clean phase will be executed first (meaning it will run all preceding【前面的】 phases of the clean lifecycle, plus【外加;加上】 the clean phase itself), and then the dependency:copy-dependencies goal, before finally executing the package phase (and all its preceding build phases of the default lifecycle).

Moreover【此外;而且】, if a goal is bound to one or more build phases, that goal will be called in all those phases.

Furthermore【此外】, a build phase can also have zero or more goals bound to it. If a build phase has no goals bound to it, that build phase will not execute. But if it has one or more goals bound to it, it will execute all those goals.

(Note: In Maven 2.0.5 and above, multiple goals bound to a phase are executed in the same order as they are declared in the POM, however multiple instances of the same plugin are not supported. Multiple instances of the same plugin are grouped to execute together and ordered in Maven 2.0.11 and above).

[top].

Some Phases Are Not Usually Called From the Command Line

The phases named with hyphenated-words【带连字符的单词】 (pre-*, post-*, or process-*) are not usually directly called【不经常直接调用】 from the command line. These phases sequence the build, producing intermediate results【中间结果】 that are not useful outside the build. In the case of invoking integration-test, the environment may be left【停留在;处于】 in a hanging state【悬挂状态?】.

Code coverage tools such as Jacoco and execution container plugins such as Tomcat, Cargo, and Docker bind goals to the pre-integration-test phase to prepare the integration test container environment. These plugins also bind goals to the post-integration-test phase to collect coverage statistics【收集覆盖率统计信息】 or decommission【停用】 the integration test container.

Failsafe and code coverage【故障安全和代码覆盖】 plugins bind goals to integration-test and verify phases. The net result【最终结果】 is test and coverage reports are available after the verify phase. If integration-test were to be called from the command line, no reports are generated. Worse is that【更糟的是】 the integration test container environment is left in a hanging state; the Tomcat webserver or Docker instance is left running【一直保持运行】, and Maven may not even【甚至可能不会】 terminate by itself【自行终止】.

[top].

Setting Up Your Project to Use the Build Lifecycle

The build lifecycle is simple enough to use【使用起来非常简单】, but when you are constructing【构造,创建】 a Maven build for a project, how do you go about【去做…做这个动作在后面】 assigning tasks【分配任务】 to each of those build phases?

Packaging

The first, and most common way, is to set the packaging for your project via the equally named POM element <packaging>. Some of the valid packaging values are jar, war, ear and pom. If no packaging value has been specified, it will default to jar.

Each packaging contains a list of goals to bind to a particular phase. For example, the jar packaging will bind the following goals to build phases of the default lifecycle.

Phaseplugin:goal for the jar packaging
process-resourcesresources:resources
compilecompiler:compile
process-test-resourcesresources:testResources
test-compilecompiler:testCompile
testsurefire:test
packagejar:jar
installinstall:install
deploydeploy:deploy

This is an almost standard set of bindings; however, some packagings handle them differently. For example, a project that is purely metadata【纯元数据】 (packaging value is pom) only binds goals to the install and deploy phases (for a complete list of goal-to-build-phase bindings of some of the packaging types, refer to the Lifecycle Reference).

Note that for【请注意,对于】 some packaging types to be available, you may also need to include a particular plugin in the <build> section of your POM and specify <extensions>true</extensions> for that plugin. One example of a plugin that requires this is the Plexus plugin, which provides a plexus-application and plexus-service packaging.

[top].

Plugins

The second way to add goals to phases is to configure plugins in your project. Plugins are artifacts that provide goals to Maven. Furthermore, a plugin may have one or more goals wherein each goal represents a capability of that plugin. For example, the Compiler plugin has two goals: compile and testCompile. The former【前者】 compiles the source code of your main code, while the latter【后者】 compiles the source code of your test code.

As you will see in the later sections, plugins can contain information that indicates which lifecycle phase to bind a goal to. Note that【请注意】 adding the plugin on its own is not enough information - you must also specify the goals you want to run as part of your build.

The goals that are configured will be added to the goals already bound to the lifecycle from the packaging selected. If more than one goal is bound to a particular phase, the order used is that those from the packaging are executed first, followed by those configured in the POM. Note that you can use the <executions> element to gain more control over the order of particular goals.

For example, the Modello plugin binds by default its goal modello:java to the generate-sources phase (Note: The modello:java goal generates Java source codes). So to use the Modello plugin and have it generate sources from a model and incorporate that into the build, you would add the following to your POM in the <plugins> section of <build>:

...
 <plugin>
   <groupId>org.codehaus.modello</groupId>
   <artifactId>modello-maven-plugin</artifactId>
   <version>1.8.1</version>
   <executions>
     <execution>
       <configuration>
         <models>
           <model>src/main/mdo/maven.mdo</model>
         </models>
         <version>4.0.0</version>
       </configuration>
       <goals>
         <goal>java</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
...

You might be wondering why that <executions> element is there. That is so that you can run the same goal multiple times with different configuration if needed. Separate executions can also be given an ID so that during inheritance or the application of profiles you can control whether goal configuration is merged or turned into an additional execution.

When multiple executions are given that match a particular phase, they are executed in the order specified in the POM, with inherited executions running first.

Now, in the case of modello:java, it only makes sense in the generate-sources phase. But some goals can be used in more than one phase, and there may not be a sensible default. For those, you can specify the phase yourself. For example, let’s say you have a goal display:time that echos the current time to the commandline, and you want it to run in the process-test-resources phase to indicate when the tests were started. This would be configured like so:

 ...
 <plugin>
   <groupId>com.mycompany.example</groupId>
   <artifactId>display-maven-plugin</artifactId>
   <version>1.0</version>
   <executions>
     <execution>
       <phase>process-test-resources</phase>
       <goals>
         <goal>time</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
...

[top].

Lifecycle Reference

The following lists all build phases of the default, clean and site lifecycles, which are executed in the order given up to the point of the one specified.

Clean Lifecycle

PhaseDescription
pre-cleanexecute processes needed prior to the actual project cleaning
cleanremove all files generated by the previous build
post-cleanexecute processes needed to finalize the project cleaning

Default Lifecycle

PhaseDescription
validatevalidate the project is correct and all necessary information is available.
initializeinitialize build state, e.g. set properties or create directories.
generate-sourcesgenerate any source code for inclusion in compilation.
process-sourcesprocess the source code, for example to filter any values.
generate-resourcesgenerate resources for inclusion in the package.
process-resourcescopy and process the resources into the destination directory, ready for packaging.
compilecompile the source code of the project.
process-classespost-process the generated files from compilation, for example to do bytecode enhancement【字节码增强】 on Java classes.
generate-test-sourcesgenerate any test source code for inclusion in compilation.
process-test-sourcesprocess the test source code, for example to filter any values.
generate-test-resourcescreate resources for testing.
process-test-resourcescopy and process the resources into the test destination directory.
test-compilecompile the test source code into the test destination directory
process-test-classespost-process the generated files from test compilation, for example to do bytecode enhancement on Java classes.
testrun tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
prepare-packageperform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package.
packagetake the compiled code and package it in its distributable format, such as a JAR.
pre-integration-testperform actions required before integration tests are executed. This may involve things such as setting up the required environment.
integration-testprocess and deploy the package if necessary into an environment where integration tests can be run.
post-integration-testperform actions required after integration tests have been executed. This may including cleaning up the environment.
verifyrun any checks to verify the package is valid and meets quality criteria【满足质量标准】.
installinstall the package into the local repository, for use as a dependency in other projects locally.
deploydone in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Site Lifecycle

PhaseDescription
pre-siteexecute processes needed prior to the actual project site generation
sitegenerate the project’s site documentation
post-siteexecute processes needed to finalize the site generation, and to prepare for site deployment
site-deploydeploy the generated site documentation to the specified web server

[top].

Built-in Lifecycle Bindings

Some phases have goals bound to them by default. And for the default lifecycle, these bindings depend on the packaging value. Here are some of the goal-to-build-phase bindings.

Clean Lifecycle Bindings

Phaseplugin:goal
cleanclean:clean

Default Lifecycle Bindings - Packaging ejb / ejb3 / jar / par / rar / war

Phaseplugin:goal
process-resourcesresources:resources
compilecompiler:compile
process-test-resourcesresources:testResources
test-compilecompiler:testCompile
testsurefire:test
packageejb:ejb or ejb3:ejb3 or jar:jar or par:par or rar:rar or war:war
installinstall:install
deploydeploy:deploy

Default Lifecycle Bindings - Packaging ear

Phaseplugin:goal
generate-resourcesear:generate-application-xml
process-resourcesresources:resources
packageear:ear
installinstall:install
deploydeploy:deploy

Default Lifecycle Bindings - Packaging maven-plugin

Phaseplugin:goal
generate-resourcesplugin:descriptor
process-resourcesresources:resources
compilecompiler:compile
process-test-resourcesresources:testResources
test-compilecompiler:testCompile
testsurefire:test
packagejar:jar and plugin:addPluginArtifactMetadata
installinstall:install
deploydeploy:deploy

Default Lifecycle Bindings - Packaging pom

Phaseplugin:goal
package
installinstall:install
deploydeploy:deploy

Site Lifecycle Bindings

Phaseplugin:goal
sitesite:site
site-deploysite:deploy

References

The full Maven lifecycle is defined by the components.xml file in the maven-core module, with associated documentation for reference.

Default lifecycle bindings are defined in a separate default-bindings.xml descriptor.

// 参考手册

See Lifecycles Reference and Plugin Bindings for default Lifecycle Reference for latest documentation taken directly from source code.

[top].

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值