что делает mvn site

Что делает mvn site

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.

Источник

Что делает mvn site

The Site Plugin is used to generate a site for the project. The generated site also includes the project’s reports that were configured in the POM.

Please read the migration guide if you want to upgrade from a previous version.

Goals Overview

The Site Plugin has seven goals:

Usage

General instructions on how to use the Site Plugin can be found on the usage page. Some more specific use cases are described in the examples given below.

In case you still have questions regarding the plugin’s usage, please have a look at the FAQ and feel free to contact the user mailing list. The posts to the mailing list are archived and could already contain the answer to your question as part of an older thread. Hence, it is also worth browsing/searching the mail archive.

If you feel like the plugin is missing a feature or has a defect, you can file a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs, or, most preferably, little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.

Examples

The following examples show how to use the Site Plugin in more advanced use cases:

Источник

Живой сайт об актуальных проектах

User Tools

Site Tools

Sidebar

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

Table of Contents

Maven FAQ

Основные ссылки по Maven:

Что такое сборка проекта, автоматизация сборки?

Что такое Maven? Как он работает?

Если собирать большие проекты с командной строки, то команда для сборки будет очень длинной, поэтому её иногда записывают в bat/sh скрипт. Но такие скрипты зависят от платформы. Для того чтобы избавиться от этой зависимости и упростить написание скрипта, используют инструменты для сборки проекта.

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

Какие преимущества Maven?

Основные преимущества Maven:

Какие недостатки Maven?

Какими аспектами управляет Maven?

Вот основные аспекты, которыми позволяет управлять Maven:

Как узнать, какую версию Maven вы используете?

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

Для чего был создан Maven?

Основной целью Maven является предоставление разработчику:

Структура и содержание проекта Maven указывается в специальном xml-файле, который назывется Project Object Model (POM), который является базовым модулем всей системы.

Какая структура каталогов в Maven?

src/main/javaApplication/Library sourcesисходный код приложения или библиотеки
src/main/resourcesApplication/Library resourcesресурсы приложения или библиотеки
src/main/filtersResource filter filesфайлы с параметрами фильтрации ресурсов
src/main/webappWeb application sourcesисходный код веб-приложения
src/test/javaTest sourcesисходный код тестов (юнит-тестов)
src/test/resourcesTest resourcesресурсы юнит тестов
src/test/filtersTest resource filter filesфайлы с параметрами фильтрации ресурсов для тестов
src/itIntegration Tests (primarily for plugins)интеграционные тесты (в основном для плагинов)
src/assemblyAssembly descriptorsдескрипторы сборки
src/siteSiteвебсайт приложения (документация)
LICENSE.txtProject’s licenseлицензионное соглашение проекта
NOTICE.txtNotices and attributions required by libraries that the project depends onзамечания и необходимые атрибуты библиотек, от зависит проект
README.txtProject’s readmeкраткое описание проекта

Где хранятся файлы классов при компиляции проекта Maven?

Что такое pom.xml?

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

содержит ссылку на схему XML, которая облегчает редактирование и проверку pom.xml :

Внутри тега project содержится основная и обязательная информация о проекте.

Какую информацию содержит pom.xml?

Среди информации которую содержит pom.xml, мы можем выделить следующие блоки:

Что такое супер POM?

Какие элементы необходимы для минимального POM?

Что такое зависимости в Maven?

Что такое артефакт в Maven?

Что такое плагин в Maven?

Что такое задача в Maven?

Что такое архетип в Maven?

Что такое репозитарий в Maven?

Какие типы репозитария существуют в Maven?

В Maven существуют три типа репозитариев:

Какая команда устанавливает JAR-файл в локальное хранилище (репозитарий)?

Какой порядок поиска зависимостей Maven?

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

Какие два файла настройки есть в Maven, как они называются и где расположены?

Что такое жизненный цикл сборки в Maven?

Назовите основные фазы жизненного цикла сборки Maven?

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

В Maven есть следующие три стандартных жизненных цикла:

Что делает команда mvn site?

создает веб-сайт проекта.

Что делает команда mvn clean?

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

Из каких фаз состоит жизненный цикл сборки Clean?

Жизненный цикл сборки Clean состоит из следующих этапов:

Из каких фаз состоит жизненный цикл сборки Default (Build)?

Здесь также необходимо уточнить два момента:

Из каких фаз состоит жизненный цикл сборки Site?

Жизненный цикл сборки Site состоит из следующих этапов:

Что сделает команда «mvn clean dependency:copy-dependencies package»?

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

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

Что такое профиль сборки (Build Profile)?

Используя профиль сборки Maven, мы можем настраивать сборку для различных окружений, таких как Development или Production.

Профили настраиваются в файле pom.xml с помощью элементов activeProfiles / profiles и запускаются различными методами.

Какие типы профилей сборки (Build Profiles) вы знаете?

В Maven существует три основных типа профилей сборки :

Как вы можете активировать профили сборки?

Профиль сборки Maven может быть активирован различными способами:

Для чего используются Maven плагины?

Maven плагины используются для:

Какие типы плагинов существуют в Maven?

В Maven существует два типа плагинов:

Когда Maven использует внешние зависимости?

Если необходимые файлы не найдены ни в центральном, ни на удалённом репозитарии, тогда для решения этой проблемы используются внешние зависимости.

Что нужно определить для внешней зависимости?

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

Какая команда создает новый проект на основе архетипа?

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

Что такое SNAPSHOT в Maven?

В чем разница между snapshot и версией?

В случае со snapshot, Maven автоматически будет подтягивать крайний snapshot ( data-service:1.0-SNAPSHOT ) каждый раз, когда будет выполнятся сборка проекта.

Что такое транзитивная зависимость в Maven?

Как Maven определяет, какую версию зависимостей использовать, когда встречается множественный вариант выбора?

Что такое область видимости зависимостей (dependency scope)? Назовите значения dependency scope.

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

Какой минимальный набор информации нужен для составления ссылки зависимостей в разделе dependencyManagement?

Как сослаться на свойство(property) определенное в файле pom.xml?

Для чего нужен элемент в POM файле?

Элемент содержит информацию, необходимую для выполнения плагина.

Каким образом можно исключить зависимость в Maven?

Что является полным именем артефакта?

Если вы не определяете никакой информации, откуда ваш POM унаследует её?

Все POM-ы наследуются от родителя, несмотря на то, определен ли он явно или нет. Это базовый POM известный как “супер POM”, он содержит значения, которые наследуются по умолчанию.

При сборке проекта Maven постоянно проверяет наличие обновлений в интернете. Можете ли вы собрать проект без интернета?

Да, можете, если в вашем локальном репозитарии есть все необходимые для сборки артефакты.

Если при сборке проекта в тестах произошла ошибка, как собрать проект без запуска тестов?

Как запустить только один тест?

Источник

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

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