mvn clean test что делает
Руководство по 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.
В следующем уроке мы изучим профиль сборки.
Mvn clean test что делает
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
Что делать, если сборка (build) с Maven проходит слишком медленно? Ведь когда сборка длится слишком долго, любой, даже самый терпеливый разработчик, может заскучать и отвлечься.
Для быстрого поиска в Google или для закладок, сразу предлагаю итоговое решение:
— для сборки проекта без тестов.
Эта история началась с того, что я выкачал довольно большой проект на Java из нашего корпоративного репозитория. Думаю, что многие, как и я, сразу собрали бы его командой:
, ну а многие командой:
Мой проект собрался за 25 минут, и каждый раз собирался так же долго, как и в первый раз.
package вместо install
Согласно жизненному циклу сборки проекта после фазы package, на которой мы получаем полноценный jar-файл, есть фаза verify, а затем install. Часто необходимо получить именно jar-файл, который нет необходимости помещать в локальный репозиторий, поэтому в данной ситуации я остановился на package и сэкономил немного времени.
Параллельная сборка
В первом случае вы указываете число потоков для использования Maven, а во втором — что необходимо использовать один поток на каждое ядро CPU.
Второй способ задания параметра, привязанный к количеству ядер, я и собираюсь использовать в своей итоговой команде.
Поэкспериментировав с количеством потоков на ядро, попробовав следующие варианты:
Инкрементальная сборка
Как мы обсуждали выше, проект чаще всего собирается командой:
Команда clean используется для очистки проекта, но так ли это нужно каждый раз при сборке? Нет, обычно мы хотим инкрементального обновления проекта, и Maven на это способен при помощи команды:
Maven собирает модуль и обновляет те модули, от которых зависит данный модуль, в случае если в них что-то поменялось.
Эта опция в разы ускоряет сборку проектов из многих модулей, в которых, как правило, вносятся точечные изменения в 1-2 модуля.
Оффлайновая сборка
Часто бывает так, что артефакты на внешних репозиториях обновляются не так уж и часто, особенно, когда это артефакты определённой версии, или эти артефакты должны поддерживаться вашими усилиями (- Добро пожаловать в новый проект!). Довольно логично в такой ситуации сообщить Maven, что не нужно каждый раз заново скачивать их из репозиториев:
Мы для лаконичности остановимся на первом варианте.
Пропуск тестов
Но при этом можно также пропустить компиляцию тестов, если выполнить команду в следующем виде:
Подведём итоги
Итак, ещё раз команда, которая получилась у нас для ускорения сборки с Maven:
Результат, показанный на собираемом мной проекте, радует: сборка вместо 25 минут стала проходить за 30 секунд.
Авторы некоторых других статей по оптимизации скорости сборки с Maven также рекомендуют использовать параметры оптимизации запуска компилятора:
— но, во-первых, я не почувствовал какого-то реального ускорения сборки, по всей видимости, из-за того, что я и так пользовался инкрементальной сборкой и процесс компиляции отнимал в этом случае не так много времени, а во-вторых, встречается достаточное количество упоминаний того, что эти параметры могут вызвать ошибки OutOfMemory и прочие проблемы.
Надеюсь, что в комментариях вы также поделитесь статистикой по ускорению сборки ваших проектов!