mvn clean verify что делает

Mvn clean verify что делает

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.

Phaseplugin:goal
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 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

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

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
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
Phaseplugin:goal
generate-resourcesear:generate-application-xml
process-resourcesresources:resources
packageear:ear
installinstall:install
deploydeploy:deploy
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
Phaseplugin:goal
package
installinstall:install
deploydeploy: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.

Источник

Фреймворк Apache Maven

Apache Maven предназначен для автоматизации процесса сборки проектов на основе описания их структуры в файле на языке POM (Project Object Model), который является подмножеством формата XML. maven позволяет выполнять компиляцию кодов, создавать дистрибутив программы, архивные файлы jar/war и генерировать документацию. Простые проекты maven может собрать в командной строке. Название программы maven вышло из языка идиш, смысл которого можно выразить как «собиратель знания».

В отличие от ant с императивной сборкой проекта, maven обеспечивает декларативную сборку проекта. То есть, в файле описания проекта содержатся не отдельные команды выполнения, а спецификация проекта. Все задачи по обработке файлов maven выполняет посредством их обработки последовательностью встроенных и внешних плагинов.

Инсталляция maven

Последнюю версию maven можно скачать в виде zip-архива со страницы загрузки на официальном сайте. После этого необходимо выполнить несколько шагов :

Чтобы убедиться, что maven установлен, необходимо в командной строке ввести следующую команду :

Должна появиться информация о версиях maven, jre и операционной системе типа :

Одной из привлекательных особенностей maven‘a является справка online, работоспособность которой можно проверить после инсталляции. К примеру справку по фазе компиляции можно получить следующей командой :

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

Репозитории проекта, repositories

Под репозиторием (repository) понимается, как правило, внешний центральный репозиторий, в котором собрано огромное количество наиболее популярных и востребованных библиотек, и локальный репозиторий, в котором хранятся копии используемых ранее библиотек.

Дополнительные репозитории, необходимые для сборки проекта, перечисляются в секции проектного файла pom.xml :

Для добавления, к примеру, библиотеки carousel-lib.jar в локальный репозиторий можно использовать команду mvn install (команда должна быть однострочной) :

В локальном репозитории «.m2» maven создаст директорию ru/carousel, в которой разместит данную библиотеку и создаст к ней описание в виде pom.xml.

Репозиторий можно также разместить внутри проекта. Описания процесса создания и размещения репозитория внутри проекта с примером можно прочитать здесь.

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

Терминология maven

В maven используется свой набор терминов и понятий. Ключевым понятием maven является артефакт (artifact) — это, по сути, любая библиотека, хранящаяся в репозитории, к которой можно отнести зависимость или плагин.

Зависимости (dependencies) представляют собой библиотеки, которые непосредственно используются в проекте для компиляции или тестирования кода.

При сборке проекта или для каких-то других целей (deploy, создание файлов проекта для Eclipse и др.) maven использует плагины (plugin).

Архетипы maven

Количество архетипов у maven‘a огромно, «на разный вкус». Как правильно выбрать нужный, чтобы создать архитектуру будущего проекта? Просматривать в консоли не очень удобно, тем более что их количество переваливает за 1500 (к примеру для версии maven 3.3.9 на моем компьютере их 1665). Поэтому можно скачать их в отдельный файл, а потом со всем этим хозяйством разбираться. Для этого необходимо выполнить следующую команду :

В результате в файле archetypes.txt можно увидеть, что-то подобное

При выполнении данной команды maven, после скачивания информации в файл, ожидает поступления команды пользователя. Т.е., находится в ожидании интерактивного ввода команд по созданию проекта определенного типа. Если файл уже создан, то прервите выполнение команды двойным нажатием клавишам Ctrl+C.

Для создания простенького maven проекта «carousel» (карусель) необходимо выполнить следующую команду :

Архитектура простого maven проекта

Следующая структура показывает директории простого maven проекта.

mvn clean verify что делает. Смотреть фото mvn clean verify что делает. Смотреть картинку mvn clean verify что делает. Картинка про mvn clean verify что делает. Фото mvn clean verify что делает

Проектный файл pom.xml располагается в корне каталога.

В зависимости от типа приложения (консольное, с интерфейсом, web, gwt и т.д.) структура может отличаться. В директории target maven собирает проект (jar/war).

На официальном сайте Apache Maven Project можно получить дополнительную информацию об архетипах (Introduction to Archetypes).

Жизненный цикл maven проекта

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

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

Фазы жизненного цикла clean

Фазы жизненного цикла default

Фазы жизненного цикла site

Стандартные жизненные циклы могут быть дополнены функционалом с помощью maven-плагинов. Плагины позволяют вставлять в стандартный цикл новые шаги (например, распределение на сервер приложений) или расширять существующие шаги.

Порядок выполнения команд maven проекта зависит от порядка вызова целей и фаз. Следующая команда

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

Зависимости, dependency

Зависимость, эта связь, которая говорит, что для некоторых фаз жизненного цикла maven проекта, требуются некоторые артефакты. Зависимости проекта описываются в секции файла pom.xml. Для каждого используемого в проекте артефакта необходимо указать GAV (groupId, artifactId, version), где

Как правило информации GAV достаточно maven‘у, для поиска указанного артефакта в репозиториях. Пример описания зависимости библиотеки JDBC для работы с БД Oracle.

Более подробная информация о зависимостях и областях их действия, а также о способе построения транзитивных зависимостей в виде дерева представлена на странице dependency в maven-проекте.

Плагины, plugins

Maven базируется на plugin-архитектуре, которая позволяет использовать плагины для различных задач (test, compile, build, deploy и т.п). Иными словами, maven запускает определенные плагины, которые выполняют всю работу. То есть, если мы хотим научить maven особенным сборкам проекта, то необходимо добавить в pom.xml указание на запуск нужного плагина в нужную фазу и с нужными параметрами. Это возможно за счет того, что информация поступает плагину через стандартный вход, а результаты пишутся в его стандартный выход.

Количество доступных плагинов очень велико и включает разнотипные плагины, позволяющие непосредственно из maven запускать web-приложение для тестирования его в браузере, генерировать Web Services. Главной задачей разработчика в этой ситуации является найти и применить наиболее подходящий набор плагинов.

Целью (goal) выполнения данного плагина является проверка «check». Можно запустить в более краткой форме :

Объявление плагина в проекте похоже на объявление зависимости. Плагины также идентифицируется с помощью GAV (groupId, artifactId, version). Например:

Объявление плагина в pom.xml позволяет зафиксировать версию плагина, задать ему необходимые параметры, определить конфигурационные параметры, привязать к фазам.

Что касается списка конфигурационных переменных плагина, то его легко можно найти на сайте maven. К примеру, для maven-compiler-plugin, на странице Apache Maven Project можно увидеть перечень всех переменных, управляющих плагином.

Разные плагины вызываются maven’ом на разных стадиях жизненного цикла. Так проект, формирующий настольное java-приложение с использованием библиотек swing или swt, имеет стадии жизненного цикла отличные от тех, что характерны для разработке enterprise application (ear). Еак например, когда выполняется команда «mvn test», инициируeтся целый набор шагов в жизненном цикле проекта: «process-resources”, «compile», «process-classes», «process-test-resources», «test-compile», «test». Упоминания этих фаз отражаются в выводимых maven-ом сообщениях :

В каждой фазе жизненного цикла проекта вызывается определенный плагин (jar-библиотека), который включает некоторое количество целей (goal). Например, плагин «maven-compiler-plugin» содержит две цели: «compiler:compile» для компиляции основного исходного кода проекта и «compiler:testCompile» для компиляции тестов. Формально, список фаз можно изменять, хотя такая ситуация случается крайне редко.

В проектном файле pom.xml можно настроить для каждого из плагинов жизненного цикла набор конфигурационных переменных, например :

В случае необходимости выполнения нестандартных действий в определенной фазе, например, на стадии генерации исходников «generate-sources», можно добавить вызов соответствующего плагина в файле pom.xml :

Самое важное в данном случае – это определить для плагина наименование фазы «execution/phase», в которую нужно встроить вызов цели плагина «goal». Фаза «generate-sources» располагается перед вызовом фазы compile и очень удобна для генерирования части исходных кодов проекта.

Описание различных плагинов представлено на странице Maven плагины для сборки проекта.

Основные исполняемые цели, goal

Использование maven часто сводится к выполнению одной из команды следующего набора, которые можно назвать целями (по аналогии с другими системами сборки типа ant, make) :

В общем случае для выполнения команды maven необходимо выполнить следующий код : «mvn цель». В качестве параметров указываются не только имена фаз, но и имена и цели плагинов в формате «mvn плагин:цель». Например, вызов фазы цикла «mvn clean» эквивалентен вызову плагина «mvn clean:clean».

Секция свойств maven проекта, properties

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

Кодировка maven проекта

При выполнении отдельных команд maven, связанных с копированием ресурсов или компиляцией, могут «выплыть» предупреждения о кодировке :

Чтобы обойти эти сообщения, необходимо включить в секцию

следующий код с указанием требуемой кодировки :

Для просмотра свойств проекта можно использовать плагин «maven-echo-plugin» :

Проектный файл, pom.xml

Структура проекта описывается в файле pom.xml, который должен находиться в корневой папке проекта. Содержимое проектного файла имеет следующий вид :

Секция build

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

Тестирование проекта

Maven позволяет запускать JUnit case приложения на тестирование. Для этого следут выполнить команду «mvn test». Отдельные команды maven, например «mvn verify», автоматически запускают тесты приложения. Тестирование можно запретить на уровне выполнения команды или в секции «properties» файла pom.xml. Подробнее информация о тестировании с использованием maven представлена здесь.

Предопределёные переменные maven

При описании проекта в pom-файле можно использовать предопределенные переменные. Их можно условно разделить на несколько групп :

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *