maven goals что такое
Maven goals что такое
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):
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, Maven will first validate the project, then will try to compile the sources, run those against the tests, package the binaries (e.g. jar), run integration tests against that package, verify the integration tests, install the verified package to the local repository, then deploy the installed package to a remote repository.
Usual Command Line Calls
If you are uncertain what you want, the preferred phase to call is
In a build environment, use the following call to cleanly build and deploy artifacts into the shared repository.
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).
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).
Some Phases Are Not Usually Called From the Command Line
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.
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
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.
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 |
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 section of your POM and specify true for that plugin. One example of a plugin that requires this is the Plexus plugin, which provides a plexus-application and plexus-service packaging.
Plugins
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 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
You might be wondering why that 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.
Lifecycle Reference
Clean Lifecycle
Phase | Description |
---|---|
pre-clean | execute processes needed prior to the actual project cleaning |
clean | remove all files generated by the previous build |
post-clean | execute processes needed to finalize the project cleaning |
Default Lifecycle
Phase | Description |
---|---|
validate | validate the project is correct and all necessary information is available. |
initialize | initialize build state, e.g. set properties or create directories. |
generate-sources | generate any source code for inclusion in compilation. |
process-sources | process the source code, for example to filter any values. |
generate-resources | generate resources for inclusion in the package. |
process-resources | copy and process the resources into the destination directory, ready for packaging. |
compile | compile the source code of the project. |
process-classes | post-process the generated files from compilation, for example to do bytecode enhancement on Java classes. |
generate-test-sources | generate any test source code for inclusion in compilation. |
process-test-sources | process the test source code, for example to filter any values. |
generate-test-resources | create resources for testing. |
process-test-resources | copy and process the resources into the test destination directory. |
test-compile | compile the test source code into the test destination directory |
process-test-classes | post-process the generated files from test compilation, for example to do bytecode enhancement on Java classes. |
test | run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed. |
prepare-package | perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package. |
package | take the compiled code and package it in its distributable format, such as a JAR. |
pre-integration-test | perform actions required before integration tests are executed. This may involve things such as setting up the required environment. |
integration-test | process and deploy the package if necessary into an environment where integration tests can be run. |
post-integration-test | perform actions required after integration tests have been executed. This may including cleaning up the environment. |
verify | run any checks to verify the package is valid and meets quality criteria. |
install | install the package into the local repository, for use as a dependency in other projects locally. |
deploy | done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects. |
Site Lifecycle
Phase | Description |
---|---|
pre-site | execute processes needed prior to the actual project site generation |
site | generate the project’s site documentation |
post-site | execute processes needed to finalize the site generation, and to prepare for site deployment |
site-deploy | deploy the generated site documentation to the specified web server |
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
Phase | plugin:goal |
---|---|
process-resources | resources:resources |
compile | compiler:compile |
process-test-resources | resources:testResources |
test-compile | compiler:testCompile |
test | surefire:test |
package | ejb:ejb or ejb3:ejb3 or jar:jar or par:par or rar:rar or war:war |
install | install:install |
deploy | deploy:deploy |
Phase | plugin:goal |
---|---|
generate-resources | ear:generate-application-xml |
process-resources | resources:resources |
package | ear:ear |
install | install:install |
deploy | deploy:deploy |
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 |
package | jar:jar and plugin:addPluginArtifactMetadata |
install | install:install |
deploy | deploy:deploy |
Phase | plugin:goal |
---|---|
package | |
install | install:install |
deploy | deploy:deploy |
Site Lifecycle Bindings
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.
Maven: Goals и Phases
На первый взгляд сборка Maven выглядит магией — мы выполняем простую команду и запускается целый жизненный цикл, состоящий из фаз, к каждой из которой привязан свой плагин и goal (иногда не один).
Давайте разберемся, что такое фазы, голы, и как они соотносятся между собой.
Как соотносятся phases и goals
Сборку с помощью Maven можно сравнить с обедом из нескольких блюд: в нем есть закуска, первое блюдо, второе блюдо, напиток и десерт — всё это фазы (phases), а все вместе — жизненный цикл. Второе блюдо может быть котлетой, а может рыбой. Конкретика задается с помощью goal (конкретная команда конкретного плагина). Например, на фазе compile по умолчанию выполняется compiler:compile — это goal с названием compile плагина compiler. Эта команда компилирует исходники. А десерт может быть шарлоткой, это тоже конкретный goal, например deploy:deploy фазы deploy.
Сложность состоит в том, что набор умолчаний в Maven велик — согласно документации, в жизненном цикле много зарезервированных фаз, в которых ничего не выполняется (например, фаза validate). Эти фазы подразумевают какой-то смысл, но зарезервированы на тот случай, если программист захочет к ним привязать какое-то свое действие.
Конкретно на фазе validate должна проверяться корректность проекта, но как именно, решает программист, если ему это надо. (А если не надо, фаза validate пропускается). Ниже мы попробуем привязать к этой фазе простейшее действие.
Есть также фазы, которые, наоборот, выполняются по умолчанию — например, фаза compile. К ней по умолчанию привязан свой плагин и goal, как уже упоминалось выше.
Узнать, что именно происходит при сборке, можно, например, запустив сборку — все goals выведутся в консоль.
Можно также вывести все goals данной фазы так:
Попробуем запросить все goal фазы compile:
То есть на фазе compile по умолчанию выполняется maven-compiler-plugin. Через двоеточие указана goal, она называется compile.
Default build lifecycle
Запустим сборку, указав фазу install:
Обратите внимание, что pom.xml практически пустой — в нем не перечислены никакие фазы и goals, они все привязаны по умолчанию к сборке jar-файла:
При этом в pom.xml даже не указано, что надо собрать jar-файл — этот формат также подразумевается по умолчанию.
Вывод в консоль показывает, какие плагины и голы выполняются при сборке:
Как видно, по очереди выполняется:
Есть в жизненном цикле еще фаза deploy — развертывание на сервер, эта последняя фаза тут не выполнялась.
Жизненный цикл (lifecycle) сборки — это последовательность фаз (phases).
Выполнение предыдущих фаз
Обратите внимание, что мы указали одну фазу install, но выполняется целый жизненный цикл со всеми предыдущими фазами, фаза install в этом цикле последняя.
Чтобы только скопировать ресурсы и скомпилировать проект, выполняем:
Чтобы, помимо этого, выполнить тесты и упаковать проект в jar, выполняем:
(при этом выполнится компиляция и другие предваряющие package фазы).
Чтобы развернуть проект на сервере, выполним:
Все предыдущие фазы, включая install, также при этом выполнятся. В pom.xml при этом должна быть указана конфигурация с данными сервера, куда деплоить проект.
В документации указана очередность фаз, она задана заранее. Там же указаны какие именно плагины и goals по умолчанию выполняются в каких фазах. Мы можем перезаписать или добавить свое действие к определенный фазе.
Попробуем добавить свое действие к двум фазам.
Как привязать к фазе свое действие
Во-первых, любое действие, которые вы добавляете к сборке, должно быть запрограммировано в виде Maven-плагина с goal (у плагина может быть и несколько goal, которые можно привязать к разным фазам). Этот плагин вы либо пишете сами, либо берете готовый. Готовых плагинов много.
Во-вторых, чтобы добавить goal к фазе, вы прописываете в pom.xml этот плагин и goal, чуть ниже показано, как. Также можно указать фазу в теге
(можно, а не нужно, потому что для плагина уже может существовать умолчательная фаза, заданная при программировании плагина; но ее может и не быть). Добавленный goal будет выполнен после всех уже привязанных по умолчанию к фазе goal-ов.
Для примера возьмем плагин, разбираемый в документации по ссылке выше. Он выводит в консоль «Hello, world». Скомпилируйте и установите его в локальную папку .m2:
Теперь можно добавить выполнение goal hello-maven-plugin:sayhi в фазы своего проекта, например в фазы compile и validate. Для этого в корень нашего почти пустого pom.xml дабавьте:
При этом сначала выполнится компиляция (так как этот goal уже привязан по умолчанию), потом напечатается «Hello, world».
Что касается фазы validate, то поскольку по умолчанию к этой фазе ничего не привязано, выполнится только наш goal sayhi (причем в самом начале, так как validate — первая фаза согласно документации).
В консоли мы увидим:
Кстати, наш goal можно выполнить и отдельно из командной строки:
Какие еще есть жизненные циклы Maven
Хотя в работе чаще используется default lifecycle, о котором мы говорили выше, он не единственный.
Всего жизненных циклов у Maven определено три:
mvn clean install
Довольно часто указывают две фазы подряд:
Да, это фазы, но они принадлежат разным циклам. Тут запускается два цикла по очереди — сначала цикл clean, а затем цикл default.
Мы не можем указать, например:
Это фазы из одного и того же цикла default, они не могут быть выдернуты из цикла и выполнены вне его (помните правило выполнения всех предыдущих фаз).
Так что хотя многие и считают, что в примере mvn clean install указаны некоторые две выбранные фазы одного цикла, это ложная догадка, на самом деле тут выполняются два цикла, а не две фазы.
Maven goals что такое
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):
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, Maven will first validate the project, then will try to compile the sources, run those against the tests, package the binaries (e.g. jar), run integration tests against that package, verify the integration tests, install the verified package to the local repository, then deploy the installed package to a remote repository.
Usual Command Line Calls
If you are uncertain what you want, the preferred phase to call is
In a build environment, use the following call to cleanly build and deploy artifacts into the shared repository.
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).
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).
Some Phases Are Not Usually Called From the Command Line
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.
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
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.
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 |
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 section of your POM and specify true for that plugin. One example of a plugin that requires this is the Plexus plugin, which provides a plexus-application and plexus-service packaging.
Plugins
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 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
You might be wondering why that 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.
Lifecycle Reference
Clean Lifecycle
Phase | Description |
---|---|
pre-clean | execute processes needed prior to the actual project cleaning |
clean | remove all files generated by the previous build |
post-clean | execute processes needed to finalize the project cleaning |
Default Lifecycle
Phase | Description |
---|---|
validate | validate the project is correct and all necessary information is available. |
initialize | initialize build state, e.g. set properties or create directories. |
generate-sources | generate any source code for inclusion in compilation. |
process-sources | process the source code, for example to filter any values. |
generate-resources | generate resources for inclusion in the package. |
process-resources | copy and process the resources into the destination directory, ready for packaging. |
compile | compile the source code of the project. |
process-classes | post-process the generated files from compilation, for example to do bytecode enhancement on Java classes. |
generate-test-sources | generate any test source code for inclusion in compilation. |
process-test-sources | process the test source code, for example to filter any values. |
generate-test-resources | create resources for testing. |
process-test-resources | copy and process the resources into the test destination directory. |
test-compile | compile the test source code into the test destination directory |
process-test-classes | post-process the generated files from test compilation, for example to do bytecode enhancement on Java classes. |
test | run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed. |
prepare-package | perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package. |
package | take the compiled code and package it in its distributable format, such as a JAR. |
pre-integration-test | perform actions required before integration tests are executed. This may involve things such as setting up the required environment. |
integration-test | process and deploy the package if necessary into an environment where integration tests can be run. |
post-integration-test | perform actions required after integration tests have been executed. This may including cleaning up the environment. |
verify | run any checks to verify the package is valid and meets quality criteria. |
install | install the package into the local repository, for use as a dependency in other projects locally. |
deploy | done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects. |
Site Lifecycle
Phase | Description |
---|---|
pre-site | execute processes needed prior to the actual project site generation |
site | generate the project’s site documentation |
post-site | execute processes needed to finalize the site generation, and to prepare for site deployment |
site-deploy | deploy the generated site documentation to the specified web server |
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
Phase | plugin:goal |
---|---|
process-resources | resources:resources |
compile | compiler:compile |
process-test-resources | resources:testResources |
test-compile | compiler:testCompile |
test | surefire:test |
package | ejb:ejb or ejb3:ejb3 or jar:jar or par:par or rar:rar or war:war |
install | install:install |
deploy | deploy:deploy |
Phase | plugin:goal |
---|---|
generate-resources | ear:generate-application-xml |
process-resources | resources:resources |
package | ear:ear |
install | install:install |
deploy | deploy:deploy |
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 |
package | jar:jar and plugin:addPluginArtifactMetadata |
install | install:install |
deploy | deploy:deploy |
Phase | plugin:goal |
---|---|
package | |
install | install:install |
deploy | deploy:deploy |
Site Lifecycle Bindings
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.