Maven Plugins
By Priya Pedamkar
Introduction to Maven Plugins
Maven Plugins is a project management tool. Maven is based on the Project Object Model i.e. POM. Primarily maven is used as a build automation tool for Java projects. Maven can be used with other programming languages e.g.: Ruby, scala, etc. Plugins are where the real action takes place in project execution.
Example: Compiling Code, Testing Code, and Creating JAR/WAR files, etc…
Web development, programming languages, Software testing & others
Types of Maven Plugins
It provides two types of plugins:
- Build Plugins: Build Plugins will be executed during the build process and they should be configured in the<build> <build/> tag of POM file.
- Reporting Plugins: Reporting Plugins will be executed during site generation and should be configured in <reporting><reporting/> tag of POM file.
Different Plugins Supported by Maven
Below are mentioned some of the different Plugins of Maven:
1. Core Plugins of Maven
Plugins refer to the default phases (i.e. clean, compile) may also have multiple objectives.
Plugin Name | Description |
Install | Install the build artifact into the local repository. |
Clean | Clean up after a build. |
Compiler | Compiles java program. |
Deploy | Deploy the build artifact to the remote repository. |
Resources | Copy the resources to the output directory for including in the JAR |
Verifier | Useful for integration tests – verify the existence of certain conditions. |
Surefire | Run the JUnit unit tests in an isolated classloader. |
Failsafe | Run the JUnit integration tests in an isolated classloader. |
2. Reporting Plugins
These Plugins generate reports and execute under generation lifecycle
Description
3. Packaging Tools/Types
These relate to packaging types
Plugin Name | Description |
EAR | Generate an EAR(Enterprise Application ARchive) from the current project |
EJB | Build an EJB (Enterprise Java Bean) from the current project. |
JAR | Build a JAR (Java ARchive) from the current project. |
RAR | Build a RAR (Roshal Archive) from the current project. |
WAR | Build a WAR (Web application ARchive) from the current project. |
Source | Build a source-JAR from the current project. |
Jlink | Build Java Run Time Image. |
App-Client/acr | Build a JavaEE application client from the current project. |
4. Miscellaneous tools available through Maven by default
These are by default tools that are available through Maven
Plugin Name | Description |
Antrun | Run a set of ant tasks from a phase of the build. |
Assembly | Build an assembly of sources or binaries. |
Archetype | Generate a skeleton project structure from an archetype. |
Dependency | Dependency manipulation and analysis. |
Enforcer | Environmental constraint or User Custom Rule Execution. |
GPG | Create signatures for the artifacts and POMS. |
Help | Get information about the working environment for the project. |
Invoker | Run a Set of Maven Projects and Verify the Output. |
Patch | Use the gnu patch tool and apply patch files to source code. |
Generate a PDF version of project documentation. | |
Plugin | Create a Maven plugin descriptor for any mojos found in the source tree, to include in the JAR. |
Release | Release the current project, update the POM. |
Remote-Resources | Copy remote resources to the output directory for inclusion in the artifact. |
SCM | Execute SCM commands for the current project. |
Stage | Assists with release staging and promotion. |
Toolchains | Allows sharing configuration across plugins. |
Scm-Publish | Publish the Maven website to an scm location. |
Configuring of Maven Plugins
The Configuration to Plug-ins are given below:
- In most cases, Plugins should be added within the build/plugin section.
- Adding plugins in the build/plugins section directly part of the default maven builds.
- Adding plugins in build/plugin management/plugins are not part of default maven build, it’s a management.
- Ordering of plugins sections within pom.xml is irrelevant in most of the cases.
- Plugin elements within build/plugins sections may be important.
- Maven 3.0.3 version plugin execution will be invoked in their order of declaration in pom.xml file, the order is required in this case it may affect the behavior of the build process.
Conclusion
Since maven is built-in plugins based architecture; it enables the users to make utilization of any application through standard inputs. Plugins are the central feature of Maven allows reuse of common build logic with multiple projects. Plugins behavior can be customized through unique plugin parameters exposed by a description of each plugin goal.
One of the most important features of maven is dependency management i.e. automatic updating and dependency closure. It also has the ability to handle multiple projects simultaneously. Dependencies and repositories are external java files required for project repositories i.e. JAR files, Maven automatically downloads the repositories from the central maven repository and puts in a local repository in case of absence.
Recommended Articles
This is a guide to Maven Plugins. Here we discuss the basic concept along with types of Plugins in Maven, Configuring Plug-ins as well as some different plugins that are supported by Maven. You can also go through our other suggested articles to learn more –
Understanding Apache Maven (Part 8): Maven Plugins
In Part 8 of the series, below, a deeper dive on Maven Plugins is covered.
In Part 4, Maven Lifecycles and Phases were introduced. A brief overview of Plugins and Goals were also included.
- Apache Maven provides standard lifecycles.
- Lifecycles have phases that execute sequentially.
- Execution of maven is done via plugins which define goals.
- Goals can be associated with phases (or may simply be run independent of phases).
What are plugins?
Maven is a plugin-execution framework. Plugins are an assembly of goals, code written as MOJOs (Maven’s plain Old Java Objects, Modern MOJOs are not restricted to being written in Java). Goals have names and can be bound to phases. A MOJO declares its goal name and optionally, a phase association, which binds the class to a part of a lifecycle.
Plugins define goals. Goals can be bound to phases. Goals from multiple plugins can be bound to a single phase.
A plugin is typically a .jar file which contains the MOJO classes and a META-INF/maven/plugins.xml . This plugins.xml is generated as a part of the maven execution of the plugin code.
Types of plugins
Broadly, plugins are of two types:
build plugins – configured in a project POM under the <build> element. Such plugins are executed as a part of the default (build) lifecycle.
reporting plugins – configured in a project POM under the <reporting> element. Such plugins are executed as a part of site lifecycle.
Furthermore, plugins can be classified as:
core plugins – Plugins where goals are bound to core phases (clean, compile, install, resources etc.)
packaging plugins – Plugins related to output artifact packaging. Examples include plugins for ear , jar , war etc.
reporting plugins – Plugins related to the site lifecycle and used to generate reports. Examples include checkstyle , javadoc , project-info-reports etc.
tooling plugins – Plugins related to general tooling during the maven execution. Examples include assembly , help , enforcer toolchains etc.
Plugins from Maven – versus – custom plugins
Official Maven plugins developed as a part of Apache Maven have a standard naming convention: maven-<plugin shortName>-plugin . This naming convention is reserved and SHOULD NOT be used by plugins which do not have a groupId of org.apache.maven.plugins and are not found on a maven repository under ord/apache/maven/plugins directory.
Plugins developed with other groupIds typically have a name of <plugin shortName>-maven-plugin .
How to learn about a plugin
Standard plugins from Apache Maven have a consistent site structure under a common site: https://maven.apache.org/plugins/index.html.
Each plugin landing page has a few menu items under its navigation panel. An Introduction page, which provides an overview of the plugin. A Goals page which lists all goals defined by the plugin and a deeper explanation of goal’s intent. A Usage page that provides configuration options and any relevant information regarding constraints for the plugin. An FAQ page for responses to frequently asked questions. There are additional pages for License and Download of the plugin as well.
In addition to the standard menu items, a plugin landing page can provide links to Examples and Project Documentation.
The plugin site is the best way to start understanding a plugin provided by Apache Maven. Plugins developed external to Apache Maven should attempt to follow similar conventions to ensure easier comprehension by the users.
How to use plugins in a project POM
Plugins are configured in a POM under either the <build> or the <reporting> or the <profiles> -> <profile> element. A plugin can be located using the standard maven G-A-V (GroupId-ArtifactId-Version) coordinates. In addition to the location coordinates, a plugin has a few other elements that are optional.
Extensions
The extensions is a flag to determine if Maven extensions from the plugin should be loaded. The value is a true or false , however, the current datatype in the schema is a String (for some technical reasons). The default value is false and it is rarely enabled. Typical use cases for enabling this is when defining a custom lifecycle or packaging types.
Inherited
Will be covered in a section below, but inherited is a boolean flag that is true by default. As with extensions the datatype in the schema is a String . Setting inherited to false prevents propagation of the configuration to any child POM of the current one.
Executions
The executions is a complex element and contains a set of execution elements. At its core, maven executes such definitions. An execution specified the set of goals to execute during the lifecycle. An execution is a complex element that has a unique id, a phase to bind one or more goals to, an inherited flag (similar to the one defined for a plugin, also set as a String datatype), a goals element which is a set of String goal elements that are bound to the phase, and a generic configuration element.
Dependencies
The dependencies is a complex element and contains a set of dependency elements. The dependency definitions listed here are used by the plugin and loaded by the plugin classloader.
Configuration
The configuration is a complex element which allows for a free-form DOM configuration used by the plugin. The configuration specifics are typically listed (and recommended, in case of custom plugins) in the Usage page for a given plugin.
A visual of the plugin element
Plugin Inheritance
Plugins have a inheritance logic similar to dependencies. A plugin declared in a parent POM is inherited into the child POM unless the parent declares the inherited flag to false . Setting the inherited flag to false breaks the inheritance.
In addition, a pluginManagement section in a POM functions the same way a dependencyManagement works for a dependency.
There is currently no equivalent in a bill-of-materials for a plugin, although, there is an open issue for introducing such a facility. Link: https://issues.apache.org/jira/browse/MNG-5588
Mixin Maven Plugin
Not officially an Apache Maven plugin, but the mixin-maven-plugin deserves a special mention. The plugin allows for including multiple pluginManagement sections without needing to inherit the plugins from a single parent. Using this plugin allows for a build behavior to be made more modular.
Apache Maven — основы
После публикации топика о Maven в комментариях возникли вопросы о том, как начать с ним работать, с чего начать, как составлять файлы pom.xml, откуда брать плагины и т.п. Данный топик будет своего рода getting started или f.a.q.
Терминология
Как в любой системе, в Maven, есть свой набор терминов и понятий.
Вся структура проекта описывается в файле pom.xml (POM – Project Object Model), который должен находиться в корневой папке проекта. Ключевым понятием Maven является артефакт — это, по сути, любая библиотека, хранящаяся в репозитории. Это может быть какая-то зависимость или плагин.
Зависимости — это те библиотеки, которые непосредственно используются в вашем проекте для компиляции кода или его тестирования.
Плагины же используются самим Maven’ом при сборке проекта или для каких-то других целей (деплоймент, создание файлов проекта для Eclipse и др.).
В самом начале работы с Maven, пользователь непременно столкнется с таким понятием как архетип. Архетип — это некая стандартная компоновка файлов и каталогов в проектах различного рода (веб, swing-проекты и прочие). Другими словами, Maven знает, как обычно строятся проекты и в соответствии с архетипом создает структуру каталогов.
Как правило, название артефакта состоит из названия группы, собственного названия и версии. К примеру Spring будет иметь вот такое название в среде Maven: org.springframework.spring:2.5.5. Последний домен означает всегда artifactId, все, что перед ним – groupId – хорошо это запомните!
На жизненном цикле останавливаться не буду, так как он хорошо описан в вышеобозначенной статье. А теперь перейдем к практике.
Установка Maven
Последнюю версию всегда можно скачать на странице загрузки на официальном сайте. Просто распаковываем архив в любую директорию. Далее необходимо создать переменную в Path, в которой необходимо указать путь к Maven. Заходим в Win + Pause – Дополнительно – Переменные среды – в верхнем окошке нажимаем Создать, вводим имя M2_HOME и значение допустим “C:\apache-maven-2.2.1”. Далее там же создаем еще одну переменную M2 со значением %M2_HOME%\bin. Так же убеждаемся, что есть переменная JAVA_HOME с путем к JDK. Ее значение должно быть примерно таким «c:\Program Files\Java\jdk1.6.0_10\». И наконец в том же окошке создаем/модифицируем переменную Path, в нее необходимо просто написать %M2%, чтобы наша папочка с исполняемым файлом Maven была видна из командной строки. Теперь необходимо проверить работоспособность нашей установки. Для этого заходим в командную строку и вводим команду
Должна появиться информация о версиях Maven, jre и операционной системе, что-то вроде:
Maven создаст вам локальный репозиторий в вашей личной папке, например в каталоге C:\Documents and Settings\username\.m2\repository
Все, Maven готов к работе, можно приступать к созданию приложения.
Создание приложения из архетипа
На сайте Maven перечислены наиболее популярные архетипы для приложений, но вы можете легко создать свой или найти более специфичный например здесь.
Итак, допустим нас интересует веб-приложение – находим подходящий архетип, называется он maven-archetype-webapp. В командной строке, в необходимом каталоге выполняем команду Maven:
Теперь мы можем лицезреть довольно наглядную структуру каталогов с говорящими названиями java – здесь будут ваши классы, webapp – здесь размещаются странички веб-приложения, resources – различного рода ресурсы в classpath (файлы конфигурации, например), test – юнит-тесты, соответственно и т.п.
Сборка проекта
Здесь все просто – выполняем команду
в корневом каталоге приложения, там, где находится файл pom.xml. Первая команда скомпилирует ваш проект и поместит его в папку target, а вторая еще и положит его к вам в локальный репозиторий.
Есть полезная функция, наподобие конвеера, то есть можно написать
и Maven сначала очистит папку target проекта, потом соберет его и положит в репозиторий.
Минимальный набор действий для работы Maven мы изучили, теперь переходим к кастомизации и добавлению зависимостей проекта.
Зависимости и репозитории
Как правило, большинство популярных библиотек находятся в центральном репозитории, поэтому их можно прописывать сразу в раздел dependencies вашего pom-файла. Например чтобы подключить Spring Framework необходимо определить следующую зависимость:
Версию хотя и можно не указывать и тогда Maven возьмет последний вариант, но я вам лично советую это делать, потому как у нас неоднократно бывали случаи, что проект просто в один момент переставал собираться или начинал падать в совершенно неожиданных и хорошо оттестированных местах, хотя вроде бы никто ничего не менял.
Специфические вещи обычно не находятся в центральном репозитории и тогда вам придется указать репозиторий производителя вручную. Для примера добавим зависимость JSF-фреймворка ajax-компонентов JBoss RichFaces.
С зависимостями все просто:
А вот репозиторий JBoss теперь необходимо прописать ручками либо в файле settings.xml, который лежит в корне вашего локального репозитория, либо в самом файле pom.xml, в зависимости от того, нужен ли данный репозиторий во всех проектах, либо в каком-то одном конкретном, соответственно:
Как правило на сайтах крупных проектов пишут всю информацию, необходимую для встраивания их библиотеки в проект на основе Maven, но бывают случаи, когда артефакт приходится искать очень и очень долго. Здесь нам очень сильно может помочь MVNrepository.com — он вам всегда подскажет где может находиться искомая библиотечка. Но если уж и там не нашлось, то из собственного опыта могу посоветовать гуглить «<название библиотеки> pom.xml». Бывает так, что проекты уже давно закрыты и в репозитории не положены потому что разработчики уже не заботятся об их распространении. Тогда остается один единственный способ – добавить файл в репозиторий вручную командой:
Последний параметр чаще всего имеет значение jar.
Плагины
Так как плагины являются такими же артефактами, как и зависимости, то они описываются практически так же. Вместо раздела dependencies – plugins, dependency – plugin, repositories – pluginRepositories, repository – pluginRepository.
Плагинами Maven делает все, даже непосредственно то, для чего он затевался – сборку проекта, только этот плагин необязательно указывать в свойствах проекта, если вы не хотите добавить какие-то фичи.
Посмотрим как настроить плагин для создания проекта для Eclipse с использованием WTP ver. 2.0. В раздел plugins нашего pom.xml прописываем следующий плагин:
Теперь идем опять таки в командную строку и выполняем команду
Ждем пока Maven найдет все библиотеки в репозитории или скачает их и вуаля – теперь наш Maven-проект можно открыть как проект eclipse. При этом библиотеки никуда не копируются как при классическом подходе, а остаются в репозитории и Eclipse делает на них ссылку через свои переменные.
Единого списка всех плагинов естественно не существует, на официальном сайте только есть поддерживаемые плагины непосредственно разработчиками Maven. Однако хотелось бы отметить, что названия плагинов довольно прямолинейны и сделав поиск по ключевым словам «maven tomcat plugin» вы скорее всего обнаружите первой ссылкой плагин для деплоймента проекта в Tomcat.
Собственный репозиторий
К сожалению сам не имею большого опыта настройки репозитория, но могу посоветовать как наиболее простой и распространенный Nexus. За дополнительной информацией следует обратиться на сайт данного проекта.
Однако нельзя оставить без внимания и достойных конкурентов в лице Artifactory и Archiva.
Maven — Plugins
For example, a Java project can be compiled with the maven-compiler-plugin’s compile-goal by running the following command.
Plugin Types
Maven provided the following two types of Plugins −
Build plugins
They execute during the build process and should be configured in the <build/> element of pom.xml.
Reporting plugins
They execute during the site generation process and they should be configured in the <reporting/> element of the pom.xml.
Following is the list of few common plugins −
Cleans up target after the build. Deletes the target directory.
Compiles Java source files.
Runs the JUnit unit tests. Creates test reports.
Builds a JAR file from the current project.
Builds a WAR file from the current project.
Generates Javadoc for the project.
Runs a set of ant tasks from any phase mentioned of the build.
We’ve used maven-antrun-plugin extensively in our examples to print data on console. Refer Build Profiles chapter. Let us understand it in a better way and create a pom.xml in C:\MVN\project folder.
Next, open the command console and go to the folder containing pom.xml and execute the following mvn command.
Maven will start processing and displaying the clean phase of clean life cycle.
The above example illustrates the following key concepts −
Plugins are specified in pom.xml using plugins element.
Each plugin can have multiple goals.
You can define phase from where plugin should starts its processing using its phase element. We’ve used clean phase.
You can configure tasks to be executed by binding them to goals of plugin. We’ve bound echo task with run goal of maven-antrun-plugin.
Maven will then download the plugin if not available in local repository and start its processing.