maven goals что такое

Руководство по Maven. Жизненный цикл сборки.

Жизненный цикл сборки в Maven – это чётко определённая последовательность фаз во время выполнения которых должны быть достигнуты определённые цели.

Типичный жизненный цикл сборки Maven выглядит следующим образом:

Фаза Действия Описание
prepare-resources Копирование ресурсов В этой фазе происходит копирование ресурсов, которое, также, может быть настроено.
compile Компиляция В этой фазе происходит компиляция исходного кода.
package Создание пакета В этой фазе, в зависимости от настроек создаётся архив JAR/WAR. Тип архива указывается в pom.xml файле.
install Установка В этой фазе происходит установка пакета в локальный/удалённый репозиторий maven.

Каждая из этих фаз имеет фазы pre и post. Они могут быть использованы для регистрации задач, которые должны быть запущены перед и после указанной фазы.

Когда Maven начинает сборку проекта, он проходит через определённую последовательность фаз и выполняет определённые задачи, которые указаны в каждой из фаз. Maven имеет следующие 3 стандартных жизненных цикла:

Задача (goal) – это специальная задача, которая относится к сборке проекта и его управлению. Она может привязываться как к нескольким фазам, так и ни к одной. Задача, которая не привязана ни к одной фазе, может быть запущена вне фаз сборки с помощью прямого вызова.

Порядок выполнения зависит от порядка вызова целей и фаз.

Например, рассмотрим команду ниже. Аргументы clean и package являются фазами сборки до тех пор, пока dependency: copy-dependencies является задачей.

В этом случае, сначала будет выполнена фаза clean, после этого будет выполнена задача dependency: copy-dependencies. После чего будет выполнена фаза package.

Жизенный цикл Clean

Когда вы выполняете команду

Задача clean Maven (clean:clean) привязывается к фазе clean в жизненном цикле сборки. Эта задача удаляет ввод сборки путём удаления директории сборки. Таким образом, когда выполняется команда mvn clean, Maven удаляет директорию сборки.

Мы можем настроить это поведение указав эти задачи в любой из фаз сборки.

Рассмотрим пример, в котором мы привяжем задачу maven-antrun-plugin:run к фазам pre-clean, clean и post-clean.

После этого выполним в терминале следующую команду:

В результате мы получим следующий результат:

Мы также можем выполнить такие же действия для фаз pre-clean и clean.

Жизненный цикл Default (Build)

Это основной жизненный цикл Maven, который используется для сборки проектов. Он включает в себя 23 фазы:

Фаза жизненного цикла Описание
validate Подтверждает, является ли проект корректным и вся ли необходимая информация доступа для завершения процесса сборки.
initialize Инициализирует состояние сборки, например, различные настройки.
generate-sources Включает любой исходный код в фазу компиляции.
process-sources Обрабатывает исходный код (подготавливает). Например, фильтрует определённые значения.
generate-resources Генерирует ресурсы, которые должны быть включены в пакет.
process-resources Копирует и отправляет ресурсы в указанную директорию. Это фаза перед упаковкой.
compile Комплирует исходный код проекта.
process-classes Обработка файлов, полученных в результате компиляции. Например, оптимизация байт-кода Java классов.
generate-test-sources Генерирует любые тестовые ресурсы, которые должны быть включены в фазу компиляции.
process-test-sources Обрабатывает исходный код тестов. Например, фильтрует значения.
test-compile Компилирует исходный код тестов в указанную директорию тестов.
process-test-classes Обрабатывает файлы, полученные в результате компиляции исходного кода тестов.
test Запускает тесты, используя приемлемый фреймворк юнит-тестирования (например, Junit).
prepare-package Выполняет все необходимые операции для подготовки пакет, непосредственно перед упаковкой.
package Преобразует скомпилированный код и пакет в дистрибутивный формат. Такие как JAR, WAR или EAR.
pre-integration-test Выполняет необходимые действия перед выполнением интеграционных тестов.
integration-test Обрабатывает и распаковывает пакет, если необходимо, в среду, где будут выполняться интеграционные тесты.
post-integration-test Выполняет действия, необходимые после выполнения интеграционных тестов. Например, освобождение ресурсов.
verify Выполняет любые проверки для подтверждения того, что пакет пригоден и отвечает критериям качества.
install Устанавливает пакет в локальный репозиторий, который может быть использован как зависимость в других локальных проектах.
deploy Копирует финальный пакет (архив) в удалённый репозиторий для, того, чтобы сделать его доступным другим разработчикам и проектам.

Необходимо уточнить два момента:

В следующем примере, мы привязываем задачу maven-antrun-plugin:run к нескольким фазам жизненного цикла сборки. Это также позволяет нам вызывать текстовые сообщения, отображая фазу жизненного цикла.

После этого выполним следующую команду:

В результате мы получим, примерно, следующий результат:

Жизненный цикл Site

Плагин Maven – Site – используется для создания докладов, документации, развёртывания и т.д.

Он включает в себя такие фазы:

В примере ниже мы прикрепляем задачу maven-antrun-plugin:run ко всем фазам жизненного цикла Site. Это позволяет нам вызывать текстовые сообщения для отображения фаз жизненного цикла.

Теперь выполним команду Maven:

В результате мы получим, примерно, следующий результат:

В этом уроке мы изучили основы жизненного цикла сборки проектов в Maven.
В следующем уроке мы изучим профиль сборки.

Источник

Maven goals

IntelliJ IDEA lets you run, debug and manage Maven goals in your project.

Run Maven goals

You can use several ways to run Maven goals such as use the Run Anything window, use the context menu in the Maven tool window, or create a run configuration for one or several Maven goals.

Читайте также:  что делает медиана в равнобедренном треугольнике

Run a Maven goal from the Run Anything window

In the Maven tool window, on the toolbar, click the button. Alternatively, press Ctrl twice to open the Run Anything window.

In the Run Anything window, start typing a name of the goal you want to execute. The window also displays a list of recent Maven goal entries.

If you have a multi-module project and need to execute a goal from the specific module then in the Run Anything window, in the top-right corner, from the Project list, select a module, or a directory you need and in the search field enter the goal’s name.

IntelliJ IDEA runs the selected goal and displays the result in the Run tool window.

Run a Maven goal from the context menu

In the Maven tool window, click Lifecycle to open a list of Maven goals.

Run a Maven goal or a set of goals via Run configuration

IntelliJ IDEA lets you create a run configuration for one specific goal or a set of several goals.

In the Maven tool window, click Lifecycle to open a list of Maven goals.

Right-click a goal for which you want to create a Run configuration. (To select several Maven goals, press Ctrl and highlight the desired goals.)

IntelliJ IDEA displays the goal under the Run Configurations node.

Configure triggers for Maven goals

IntelliJ IDEA lets you run Maven goals before your project’s execution or set other conditions using the goal activation configuration.

In the Maven tool window, click Lifecycle to open a list of goals.

In the list that opens, right-click the goal for which you want to set a trigger.

From the context menu, select an activation phase.

For example, when you use the Execute Before Build action as a trigger, the goal with such trigger is executed before you run the project’s build action ( Build | Build Project ). If the build action is delegated to Maven, then the Maven install command is executed. When you use Execute Before Rebuild, the goal with such trigger is executed before you run the project’s rebuild action ( Build | Rebuild Project ). If the rebuild action is delegated to Maven, then the Maven clean,install commands are executed.

The name of the activation is added to the selected goal in the Maven tool window.

You can also create a run/debug configuration that would depend on a Maven goal.

From the main menu, select Run | Edit Configurations to open the run/debug configuration for your project.

In the Select Maven Goal dialog, specify a project and a goal that you want to execute before launching the project.

Associate Maven goals with keyboard shortcuts

You can associate a Maven goal with a keyboard shortcut and execute goals with a single key.

In the Maven tool window, right-click the desired goal.

In the Keymap dialog, under the Maven node navigate to your goal.

Right-click the goal and from the list that opens, select a type of the shortcut you want to assign.

The shortcut is displayed against your goal in the Maven tool window.

While in the Keymap dialog, you can add a new goal to which you want to assign a shortcut.

The goal is added to the list under the Maven node. Now you can configure the shortcut.

Debug Maven goals

You can create a regular debug configuration for one or several Maven goals. You can also select a goal in the Maven tool window and start a debugging session.

Debug a Maven goal

You can start a debugging session for a single Maven goal or a Maven run configuration that may contain more than one Maven goal.

Open the Maven tool window.

Under the Lifecycle node, select a goal for which you want to start a debugging session. (Look for existing Maven run configurations under the Run Configurations node to start a debugging session for the created configuration.)

Источник

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):

Читайте также:  miso soup что это

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.

Источник

Сказочный портал