Какой командой можно узнать версию maven установленную на пк

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 Команды

Maven — это инструмент управления и понимания программных проектов, разработанный Apache. Первоначально он был выпущен в июле 2004 года. Он в основном используется для создания проектов, написанных на C #, Ruby, Scala и других языках. Maven очень стабилен и предоставляет различные плагины, которые могут помочь в создании PDF-версий, а также создать список всех последних изменений, которые были сделаны. Его легко использовать, поскольку каждый проект имеет объектную модель проекта, которая представляет собой XML-файл, который содержит все детали проекта. Кроме того, можно легко перенести любые новые функции через Maven. Давайте посмотрим на команды maven, которые используются.

Основные команды Maven

Ниже приведены основные команды Maven, о которых вам следует знать.

  • Mvn –version: эта команда помогает нам узнать текущую версию Maven, которая установлена

  • Создание проекта: Для создания проекта с использованием архитектуры MVN ниже должна использоваться команда maven.

архетип mvn: генерировать -DgroupId = com.mycompany.app -DartifactId = my-app -DarchetypeArtifactId = maven-archetype-quickstart -DarchetypeVersion = 1.4 -DinteractiveMode = false

Шаблоны, которые использует maven, называются архетипами. С помощью приведенной выше команды Maven получит все архетипы. Он выполнит все настройки и создаст рабочий проект. Эту архитектуру можно упростить, предоставив свойство archetypeArtifactId, которое помогает легко создавать приложения.

  • Пакет MVN: эта команда используется для выполнения всех фаз Maven до фазы пакета. Он выполняет работу по компиляции, проверке и сборке проекта. Он создает JAR-файл и помещает его в указанную папку в указанном проекте.

  • mvn clean install: эта команда maven помогает выполнить жизненный цикл чистой сборки и устанавливает фазу сборки в цикле сборки по умолчанию. Жизненные циклы этой сборки могут иметь фазы сборки, и внутри каждой сборки существуют разные цели сборки. Кроме того, это гарантирует, что цель сборки удаляется для новой сборки, и добавляет чистую цель.

  • mvn compile: эта команда используется для компиляции исходного кода. Он также компилирует классы, которые хранятся в определенной цели или классе.

  • mvn test: Maven также предоставляет возможность модульного тестирования определенных кодов. Он запускает тесты с использованием подходящих сред тестирования.

  • Mvn развертывания

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

  • мвн сайт

Эта команда создает сайт, основанный на информации о проекте.

Сгенерированный документ можно увидеть под целью / сайтом.

  • Выполнить задание maven build

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

  • maven.javadoc.skip

Эта команда используется для пропуска создания и упаковки любого указанного файла Javadoc jar.

Промежуточные Maven Команды

  1. mvn help: description — Эта команда помогает получить атрибуты плагина. Вся информация, касающаяся плагина, может быть найдена этой командой maven.
  2. mvn help :ffective-pom — с помощью этой команды пользователь может получить эффективный POM в виде XML. Этот XML может использоваться для текущей сборки и для активных профилей, которые присутствуют в проекте.
  3. mvn dependency: analysis — Для анализа зависимостей, присутствующих в проекте, в отношении неиспользуемых отпечатков, устаревших зависимостей и т. д., эта команда может быть использована.
  4. mvn dependency: tree — эта команда выводит полное дерево зависимостей всего проекта. Это полезно для получения всех транзитивных зависимостей и получения всех конфликтов, если они есть из-за версии. Эта команда выводит все различные зависимости.
  5. источник.пропустить : эта команда maven пропускает полную упаковку исходных файлов в проекте.
  6. maven.test.пропустить — если пользователь хочет пропустить определенный тестовый скрипт из компиляции и выполнения всех тестов, то эту команду можно использовать. Он может пропустить как единицу, так и интеграцию для теста для любого приложения
  7. groups = (TestNG Group Name (s)) — эта команда указывает группу модульных тестов TestNG, которые присутствуют и которые будут выполнены в текущей сборке. Он запускает всю группу теста. Если группа не указана, то будут выполнены все модульные тесты.
  8. prepare-package — с помощью этой команды maven выполняются все действия для любой операции, которая требуется для подготовки любого пакета.
  9. предварительный интеграционный тест — выполняет все действия, необходимые для интеграционных тестов, которые будут выполнены. Это может также очистить окружающую среду.
  10. mvn help : ffective -pom — запустите эту команду, чтобы получить самый минимальный проект Maven pom.xml.

Расширенные команды Maven

  1. Возобновление сборок : чтобы эта опция работала и возобновлялась сборка, можно использовать опцию -rf или -resume. Его можно использовать, если пользователь работает с большим многомодульным проектом, и пользователь хочет перезапустить сборку любого проекта.
  2. Создание подмножества проектов : когда пользователь указывает опцию -am, Maven создает все различные проекты, которые есть в указанном проекте. В нем могут быть проекты, которые прямо или косвенно зависят от основного проекта.
  3. Создание Maven Wrapper : Существует два способа создания Maven Wrapper.
  • cd (ваш-проект)
  • mvn -N io.takari: maven: обертка

Эта команда помогает в создании оболочки Maven для конкретного проекта с последними доступными версиями Maven.

Советы и рекомендации по использованию команд Maven

  1. Параметр Maven pl : эта команда используется для создания конкретных проектов реакторов. Нет необходимости запускать весь проект.
  2. Отладка юнит-тестов: плагин maven-surefire помогает в запуске юнит-тестов. Этот плагин вызывает фазу тестирования, а также помогает в построении жизненного цикла.

Вывод

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

Рекомендуемые статьи

Это было руководство к Maven Commands. Здесь мы обсудили как основные, так и расширенные команды Maven и некоторые непосредственные команды Maven. Вы также можете посмотреть следующую статью, чтобы узнать больше —

20+ Maven Commands and Options (Cheat Sheet)

20+ Maven Commands and Options (Cheat Sheet)

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

If you are working on Java, you must know Maven. Maven is the most popular project and dependency management tool for Java applications. Maven provides a lot of commands and options to help us in our day to day tasks.

Maven Commands

Let’s look into some popular and must know maven commands. We will use a sample Maven project to showcase the command output.

1. mvn clean

This command cleans the maven project by deleting the target directory. The command output relevant messages are shown below.

2. mvn compiler:compile

This command compiles the java source classes of the maven project.

3. mvn compiler:testCompile

This command compiles the test classes of the maven project.

4. mvn package

This command builds the maven project and packages them into a JAR, WAR, etc.

The output shows the location of the JAR file just before the “BUILD SUCCESS” message. Notice the package goal executes compile, testCompile, and test goals before packaging the build.

5. mvn install

This command builds the maven project and installs the project files (JAR, WAR, pom.xml, etc) to the local repository.

6. mvn deploy

This command is used to deploy the artifact to the remote repository. The remote repository should be configured properly in the project pom.xml file distributionManagement tag. The server entries in the maven settings.xml file is used to provide authentication details.

7. mvn validate

This command validates the maven project that everything is correct and all the necessary information is available.

8. mvn dependency:tree

This command generates the dependency tree of the maven project.

9. mvn dependency:analyze

This command analyzes the maven project to identify the unused declared and used undeclared dependencies. It’s useful in reducing the build size by identifying the unused dependencies and then remove it from the pom.xml file.

10. mvn archetype:generate

Maven archetypes is a maven project templating toolkit. We can use this command to generate a skeleton maven project of different types, such as JAR, web application, maven site, etc. Recommended Reading: Creating a Java Project using Maven Archetypes

11. mvn site:site

This command generates a site for the project. You will notice a “site” directory in the target after executing this command. There will be multiple HTML files inside the site directory that provides information related to the project.

Maven Site CommandMaven site Command

12. mvn test

This command is used to run the test cases of the project using the maven-surefire-plugin .

13. mvn compile

It’s used to compile the source Java classes of the project.

14. mvn verify

This command build the project, runs all the test cases and run any checks on the results of the integration tests to ensure quality criteria are met.

Maven Options

Maven provides a lot of command-line options to alter the maven build process. Let’s look at some of the important maven options.

15. mvn -help

This command prints the maven usage and all the available options for us to use.

Maven HelpMaven Help

16. mvn -f maven-example-jar/pom.xml package

This command is used to build a project from a different location. We are providing the pom.xml file location to build the project. It’s useful when you have to run a maven build from a script.

17. mvn -o package

This command is used to run the maven build in the offline mode. It’s useful when we have all the required JARs download in the local repository and we don’t want Maven to look for any JARs in the remote repository.

18. mvn -q package

Runs the maven build in the quiet mode, only the test cases results and errors are displayed.

19. mvn -X package

Prints the maven version and runs the build in the debug mode. It’s opposite of the quiet mode and you will see a lot of debug messages in the console.

Mvn X Debug Modemvn -X Debug Mode

20. mvn -v

Used to display the maven version information.

21. mvn -V package

This command prints the maven version and then continue with the build. It’s equivalent to the commands mvn -v;mvn package .

22. mvn -DskipTests package

The skipTests system property is used to skip the unit test cases from the build cycle. We can also use -Dmaven.test.skip=true to skip the test cases execution.

23. mvn -T 4 package

This command tells maven to run parallel builds using the specified thread count. It’s useful in multiple module projects where modules can be built in parallel. It can reduce the build time of the project.

Maven Commands Cheat Sheet

Maven Commands Cheat SheetMaven Commands Cheat Sheet

References

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Какой командой можно узнать версию maven установленную на пк

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

This chapter focuses on the various ways in which Maven can be customized at runtime. It also provides some documentation of special features such as the ability to customize the behavior of the Maven Reactor and how to use the Maven Help plugin to obtain information about plugins and plugin goals.

Maven Command Line Options

The following sections detail Maven’s command line options.

To define a property use the following option on the command line:

Defines a system property

This is the option most frequently used to customized the behavior of Maven plugins. Some examples of using the -D command line argument:

Properties defined on the command line are also available as properties to be used in a Maven POM or Maven Plugin. Form more information about referencing Maven properties, see [resource-filtering].

Properties can also be used to activate build profiles. For more information about Maven build profiles, see [profiles].

To list the available command line parameters, use the following command line option:

Display help information

Executing Maven with this option produces the following output:

If you are looking for information about the goals and parameters available from a specific Maven plugin, see Using the Maven Help Plugin.

Using Build Profiles

To activate one or more build profiles from the command line, use the following option:

Comma-delimited list of profiles to activate

For more information about build profiles, see [profiles].

Displaying Version Information

To display Maven version information, use one of the following options on the command line:

Display version information WITHOUT stopping build

Display version information

Both of these options produce the same version information output, but the -v option will terminate the Maven process after printing out the version. You would use the -V option if you wanted to have the Maven version information present at the beginning of your build’s output. This can come in handy if you are running Maven in a continuous build environment and you need to know what version of Maven was used for a particular build.

Running in Offline Mode

If you ever need to use Maven without having access to a network, you should use the following option to prevent any attempt to check for updates to plugins or dependencies over a network:

When running with the offline option enabled, Maven will not attempt to connect to a remote repository to retrieve artifacts.

Using a Custom POM or Custom Settings File

If you don’t like the ‘pom.xml’ file name, the location of your user-specific Maven settings, or the default location of your global settings file, you can customize any of these things with the following options:

Forces the use of an alternate POM file

Alternate path for the user settings file

-gs, —global-settings <file>

Alternate path for the global settings file

The following commands allow you to use Maven to encrypt passwords for storage in a Maven settings file:

Encrypt master security password

-ep, —encrypt-password <password>

Encrypt server password

Dealing with Failure

The following options control how Maven reacts to a build failure in the middle of a multi-module project build:

Only fail the build afterwards; allow all non-impacted builds to continue

Stop at first failure in reactorized builds

NEVER fail the build, regardless of project result

The -fn and -fae options are useful options for multi-module builds that are running within a continuous integration tool like Hudson. The -ff option is very useful for developers running interactive builds who want to have rapid feedback during the development cycle.

Controlling Maven’s Verbosity

If you want to control Maven’s logging level, you can use one of the following three command line options:

Produce execution error messages

Produce execution debug output

Quiet output — only show errors

The -q option only prints a message to the output if there is an error or a problem.

The -X option will print an overwhelming amount of debugging log messages to the output. This option is primarily used by Maven developers and by Maven plugin developers to diagnose problems with Maven code during development. This -X option is also very useful if you are attempting to diagnose a difficult problem with a dependency or a classpath.

The -e option will come in handy if you are a Maven developer, or if you need to diagnose an error in a Maven plugin. If you are reporting an unexpected problem with Maven or a Maven plugin, you will want to pass both the -X and -e options to your Maven process.

Running Maven in Batch Mode

To run Maven in batch mode use the following option:

Run in non-interactive (batch) mode

Batch mode is essential if you need to run Maven in a non-interactive, continuous integration environment. When running in non-interactive mode, Maven will never stop to accept input from the user. Instead, it will use sensible default values when it requires input.

Downloading and Verifying Dependencies

The following command line options affect the way that Maven will interact with remote repositories and how it verifies downloaded artifacts:

Fail the build if checksums don’t match

Warn if checksums don’t match

Forces a check for updated releases and snapshots on remote repositories

If you are concerned about security, you will want to run Maven with the -C option. Maven repositories maintain an MD5 and SHA1 checksum for every artifact stored in a repository. Maven is configured to warn the end-user if an artifact’s checksum doesn’t match the downloaded artifact. Passing in the -C option will cause Maven to fail the build if it encounters an artifact with a bad checksum.

The -U option is useful if you want to make sure that Maven is checking for the latest versions of all SNAPSHOT dependencies.

There will be times when you simply want to run a Maven build without having Maven descend into all of a project’s submodules. You can do this by using the following command line option:

Prevents Maven from building submodules. Only builds the project contained in the current directory.

Running this will only cause Maven to execute a goal or step through the lifecycle for the project in the current directory. Maven will not attempt to build all of the projects in a multi-module project when you use the -N command line option.

Using Advanced Reactor Options

Starting with the Maven 2.1 release, there are new Maven command line options which allow you to manipulate the way that Maven will build multimodule projects. These new options are:

Resume reactor from specified project

Build specified reactor projects instead of all projects

If project list is specified, also build projects required by the list

If project list is specified, also build projects that depend on projects on the list

Advanced Reactor Options Example Project

The example in this section is a skeleton of a complex multimodule project that is used to illustrate the advanced reactor options. While it is possible to read this section without the example code, you might want to download the example code and follow along, experimenting with the various options as you learn how to use the advanced reactor options. This section’s example project may be downloaded with the book’s example code at:

Unzip this archive in any directory, and then go to the ‘ch-running/’ directory. There you will see a directory named ‘sample-parent/’. All of the examples in this section will be executed from the ‘examples/ch-running/sample-parent/’ directory in the examples distribution. The sample-parent/ directory contains the multimodule project structure shown in Directory Structure of Sample Multi-module Project.

running aro project dir

This project approximates the structure of a real-world enterprise project: the sample-model project contains a set of foundational model objects used throughout the system, the sample-util project would contain utility code, the sample-persist project would contain logic that deals with persisting objects to a database, and the other projects would all be combined to produce the various GUI and Web-based interfaces that comprise a very complex system. Dependencies within Sample Multi-module Project captures the dependencies between each of these sample modules.

running aro dependencies

If you go into the ‘sample-parent/’ project directory and run mvn clean, you will see that the Maven Reactor reads all of the project dependencies and comes up with the following build order for these projects as shown in Order of Project Builds in Maven Reactor.

The -rf or —resume-from option can come in handy if you want to tell the Maven Reactor to resume a build from a particular project. This can be useful if you are working with a large multimodule project and you want to restart a build at a particular project in the Reactor without running through all of the projects that precede it in the build order.

Assume that you are working on the multi-module project with the build order shown in Order of Project Builds in Maven Reactor and that your build ran successfully up until Maven encountered a failing unit test in sample-client-connector. With the -rf option, you can fix the unit test in simple-client-connector and then run mvn -rf sample-client-connect from the ‘sample-parent/’ directory to resume the build with the final three projects.

Specifying a Subset of Projects

The -pl or —projects option allows you to select a list of projects from a multimodule project. This option can be useful if you are working on a specific set of projects, and you’d rather not wait for a full build of a multi-module project during a development cycle.

Assume that you are working on the multi-module project with the build order shown in Order of Project Builds in Maven Reactor and that you are a developer focused on the sample-rest and sample-client-connector projects. If you only wanted Maven to build the sample-rest and sample-client-connector project, you would use the following syntax from the ‘sample-parent/’ directory:

Making a Subset of Projects

If you wanted to run a portion of the larger build, you would use the -pl or —projects option with the -am or —also-make option. When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.

If you are working on the multi-module project with the build order shown in Order of Project Builds in Maven Reactor and you were only interested in working on the sample-services project, you would run mvn -pl simple-services -am to build only those projects

Making Project Dependents

While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or —also-make-dependents option configures Maven to build a project and any project that depends on that project. When using —also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

If you are working on the multi-module project with the build order shown in Order of Project Builds in Maven Reactor and you wanted to make sure that your changes to sample-services did not introduce any errors into the projects that directly or indirectly depend on sample-services, you would run the following command:

Resuming a «make» build

When using —also-make, Maven will execute a subset of the larger build as shown in Making a Subset of Projects. Combining —project, —also-make, and —resume-from provides you with the ability to refine your build even further. The -rf or —resume-from resumes the build from a specific point in the Reactor build order.

In this example, the build is resumed from sample-services which omits the sample-persist and sample-model projects from the build. If you are focused on individual components and you need to accelerate your build times, using these advanced reactor options together is a great way to skip portions of your large multi-module project build. The —resume-from argument also works with —also-make-dependents.

Using the Maven Help Plugin

Throughout this book, we introduce Maven plugins, talking about Maven Project Object Model (POM) files, settings files, and profiles. There are going to be times when you need a tool to help you make sense of some of the models that Maven is using and what goals are available on a specific plugin. The Maven Help plugin allows you to list active Maven profiles, display an effective POM, print the effective settings, or list the attributes of a Maven plugin.

The Maven Help plugin has four goals. The first three goals — active-profiles, effective-pom, and effective-settings — describe a particular project and must be run in the base directory of a project. The last goal — describe — is slightly more complex, showing you information about a plugin or a plugin goal. The following commands provide some general information about the four goals:

Lists the profiles (project, user, global) which are active for the build.

Displays the effective POM for the current build, with the active profiles factored in.

Prints out the calculated settings for the project, given any profile enhancement and the inheritance of the global settings into the user-level settings.

Describes the attributes of a plugin. This need not run under an existing project directory. You must at least give the groupId and artifactId of the plugin you wish to describe.

Describing a Maven Plugin

Once you start using Maven, you’ll spend most of your time trying to get more information about Maven Plugins: How do plugins work? What are the configuration parameters? What are the goals? The help:describe goal is something you’ll be using very frequently to retrieve this information. With the plugin parameter you can specify a plugin you wish to investigate, passing in either the plugin prefix (e.g. maven-help-plugin as help) or the groupId:artifact[:version], where version is optional. For example, the following command uses the Help plugin’s describe goal to print out information about the Maven Help plugin.

Executing the describe goal with the plugin parameter printed out the Maven coordinates for the plugin, the goal prefix, and a brief description of the plugin. While this information is helpful, you’ll usually be looking for more detail than this. If you want the Help plugin to print a full list of goals with parameters, execute the help:describe goal with the parameter full as follows:

This option is great for discovering all of a plugin’s goals as well as their parameters. But sometimes this is far more information than necessary. To get information about a single goal, set the mojo parameter as well as the plugin parameter. The following command lists all of the information about the Compiler plugin’s compile goal.

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

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