Как собрать простейшую java программу с помощью maven

Сборка Java кода

Теперь все готово для сборки проекта Maven’ом. Вы можете выполнить несколько этапов жизненного цикла сборки,
включая компиляцию кода, создание библиотеки пакета(такого, как JAR-файл) и установку библиотеки в
локальный репозиторий Maven зависимостей.

Попробуйте собрать, выполнив команду, приведенную ниже:

Этим вы запустите Maven, передав ему указание на выполнение задачи compile. Когда он закончит,
вы должны найни скомпилированные .class файлы в target/classes директории.

Вряд ли вы захотите распостранять или работать напрямую с .class файлами, поэтому
вам полее подойдет выполнение задачи package:

Задача package включает компиляцию вашего Java кода, запуск тестов, а в конце упаковывает
в JAR-файл в target директории. Название JAR-файла будет основано на
и . К примеру, с минимальным pom.xml(см. выше), JAR-файл будет иметь
название gs-maven-initial-0.1.0.jar.

Если вы изменили значение с «jar» на «war», то результатом будет
WAR-файл в target директории вместо JAR-файла.

Maven также хранит репозиторий зависимостей на вашей локальной машине(обычно в .m2/repository
директории в вашей домашней папке) для быстрого доступа к зависимостям проекта. Если вы хотите
добавить JAR-файл вашего проекта в локальный репозиторий, тогда вам необходимо выполнить задачу :

Задача install включает компиляцию, тестирование, упаковку кода проекта, а затем
копирование в локальный репозиторий, тем самым другие проекты смогут ссылаться на него как на зависимость.

Говоря о зависимостях, пришло время объявлять зависимости в Maven сборке.

Single Project Setup

This can look like this:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}</version>
  ...
</project>

This is of course a simple situation where we use only for brevity to show the general course.

Based on the above pom you can build your project using:

mvn clean package

But wait there is a problem? Which version will the artifacts have? So you need to define the version for your artifacts. The first possibility is to use the command line like this:

mvn -Drevision=1.0.0-SNAPSHOT clean package

This will become cumbersome over the time. So the other solution for this is to simply use a property inside the pom file which looks like this:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}</version>
  ...
  <properties>
    <revision>1.0.0-SNAPSHOT</revision>
  </properties>
</project>

So now you can simply call Maven as usual like .

You can of course change the version via the command line like this:

mvn -Drevision=2.0.0-SNAPSHOT clean package

Of course you can use the file for this.

A note about the used properties. You can only use those named , and/or and not other named properties like this:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}</version>
  ...
  <properties>
    <revision>1.0.0-${buildNumber}-SNAPSHOT</revision>
  </properties>
</project>

The above example will not work as expected. If you like to have more flexibility you can use a combination of the different properties like this:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}${sha1}${changelist}</version>
  ...
  <properties>
    <revision>1.3.1</revision>
    <changelist>-SNAPSHOT</changelist>
    <sha1/>
  </properties>
</project>

If you like to make a version this can simply being achieved by using this:

mvn -Drevision=2.0.0 clean package

Another usage example can be to make a release which can be done via (version 1.3.1):

mvn -Dchangelist= clean package

Or if you like to make a release with another version:

mvn -Drevision=2.7.8 -Dchangelist= clean package

Объявление зависимостей

Простой «Hello World» пример полностью автономный и не зависит от каких-либо дополнительных библиотек.
Однако, большинство приложений зависит от внешних библиотек, с реализацией распостраненного и/или
сложного функционала.

К примеру, предположим, что в дополнение к «Hello World!» вы хотите, чтобы приложение печатало текущую дату и время.
Вы могли бы использовать функциональность из стандартных(native) Java библиотек, но мы можем сделать это
и другими интересными способами, например с помощью Joda Time библиотеки.

Для начала, изменим , как показано ниже:

Здесь использует Joda Time класс для получения и печати текущего времени.

Если бы вы запустили для сборки проекта сейчас, то получили бы ошибку сборки,
потому что вы не объявили Joda Time компилируемую зависимость в сборке. Вы можете это исправить,
добавив следующие строки в pom.xml(в пределах элемента):

Этот блок XML объявляет список зависимостей проекта. В частности, он объявляет единственную зависимость от
Joda Time библиотеки. В элементе, зависимость определяется через описание
трех вложенных элементов:

  • — группа или организация, к которой принадлежит зависимость.
  • — необходимая библиотека
  • — версия необходимой библиотеки

По умолчанию, все зависимости определены как зависимости. Т.е. они должны быть
доступны во время компиляции(а если вы собираете WAR-файл, то в /WEB-INF/lib каталоге). Кроме того,
вы можете добавить элемент, с одним из значений:

  • — зависимости, которые требуются для компиляции кода проекта,
    но которые будут доступны во время выполнения кода контейнером(например, Java Servlet API)
  • — зависимости, которые используются для компиляции и запуска тестов,
    но не требуемые для сборки или выполнения кода проекта

Сейчас, если вы выполните или , Maven должен
будет разрешить Joda Time зависимость из Maven Central репозитория и успешно собрать проект.

Здесь полная версия :

Feature Summary

The following are the key features of Maven in a nutshell:

  • Simple project setup that follows best practices — get a new project or module started in seconds
  • Consistent usage across all projects — means no ramp up time for new developers coming onto a project
  • Superior dependency management including automatic updating, dependency closures (also known as transitive dependencies)
  • Able to easily work with multiple projects at the same time
  • A large and growing repository of libraries and metadata to use out of the box, and arrangements in place with the largest Open Source projects for real-time availability of their latest releases
  • Extensible, with the ability to easily write plugins in Java or scripting languages
  • Instant access to new features with little or no extra configuration
  • Ant tasks for dependency management and deployment outside of Maven
  • Model based builds: Maven is able to build any number of projects into predefined output types such as a JAR, WAR, or distribution based on metadata about the project, without the need to do any scripting in most cases.
  • Coherent site of project information: Using the same metadata as for the build process, Maven is able to generate a web site or PDF including any documentation you care to add, and adds to that standard reports about the state of development of the project. Examples of this information can be seen at the bottom of the left-hand navigation of this site under the «Project Information» and «Project Reports» submenus.
  • Release management and distribution publication: Without much additional configuration, Maven will integrate with your source control system (such as Subversion or Git) and manage the release of a project based on a certain tag. It can also publish this to a distribution location for use by other projects. Maven is able to publish individual outputs such as a JAR, an archive including other dependencies and documentation, or as a source distribution.
  • Dependency management: Maven encourages the use of a central repository of JARs and other dependencies. Maven comes with a mechanism that your project’s clients can use to download any JARs required for building your project from a central JAR repository much like Perl’s CPAN. This allows users of Maven to reuse JARs across projects and encourages communication between projects to ensure that backward compatibility issues are dealt with.

Apache Maven Install Plugin

The Install Plugin is used during the install phase to add artifact(s) to the local repository. The Install Plugin uses the information in the POM (groupId, artifactId, version) to determine the proper location for the artifact within the local repository.

The local repository is the local cache where all artifacts needed for the build are stored. By default, it is located within the user’s home directory (~/.m2/repository) but the location can be configured in ~/.m2/settings.xml using the <localRepository> element.

Goals Overview

The Install Plugin has 3 goals:

  • install:install is used to automatically install the project’s main artifact (the JAR, WAR or EAR), its POM and any attached artifacts (sources, javadoc, etc) produced by a particular project.
  • install:install-file is mostly used to install an externally created artifact into the local repository, along with its POM. In that case the project information can be taken from an optionally specified pomFile, but can also be given using command line parameters.
  • install:help displays help information on maven-install-plugin.

Important Note for Version 3.0.0+

The install:install goal does not support creating checksums anymore via -DcreateChecksum=true cause this option has been removed. Details can be found in MINSTALL-143.

Usage

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

If you feel like the plugin is missing a feature or has a defect, you can fill 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

To provide you with better understanding on some usages of the Maven Install Plugin, you can take a look into the following examples:

  • Installing a Custom POM
  • Generating a Generic POM
  • Creating Checksums
  • Updating Release Info
  • Installing an Artifact to a Specific Local Repository Path
  • Installing Secondary Artifacts

Плагины

Плагины-это такие же артефакт, как и зависимости, поэтому описываются практически так же.

Вместо раздела dependencies-plugins, dependency-plugin, repositories-pluginRepositories, repository-pluginRepository.

Плагинами maven делает все, даже сборку проекта.

Настройка плагина ля создания проекта для Eclipse с использованием WTP ver. 2.0.

В разделе plugins файла pom.xml прописываем плагин:

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-eclipse-plugin</artifactId>

<configuration>

<wtpversion>2.0</wtpversion>

</configuration>

</plugin>

Теперь идем в командную строку и выполняем:

mvn eclipse:eclipse

Ждем пока Maven найдет все библиотеки в репозитории или скачает их и теперь Maven-проект можно открыть как проект Eclipse.

Однако плагины довольно легко найти, например по запросу «maven tomcat  plugin«.

Заключение:

Maven, в отличие от Ant, описывает конечную структуру проекта, а не пути к ее достижению.

Как соотносятся phases и goals

Сборку с помощью Maven можно сравнить с обедом из нескольких блюд: в нем есть закуска, первое блюдо, второе блюдо, напиток и десерт – всё это фазы (phases), а все вместе – жизненный цикл. Второе блюдо может быть котлетой, а может рыбой. Конкретика задается с помощью goal (конкретная команда конкретного плагина). Например, на фазе compile по умолчанию выполняется compiler:compile – это goal с названием compile плагина compiler. Эта команда компилирует исходники. А десерт может быть шарлоткой, это тоже конкретный goal, например deploy:deploy фазы deploy.

К каждой фазе можно привязать несколько голов, а можно ни одного – тогда фаза просто пропускается при сборке.

Сложность состоит в том, что набор умолчаний в Maven велик –  согласно документации, в жизненном цикле много зарезервированных , в которых ничего не выполняется (например, фаза validate). Эти фазы подразумевают какой-то смысл, но зарезервированы на тот случай, если программист захочет к ним привязать какое-то свое действие.
Конкретно на фазе validate должна проверяться корректность проекта, но как именно, решает программист, если ему это надо. (А если не надо, фаза validate пропускается). Ниже мы попробуем привязать к этой фазе простейшее действие.

Есть также фазы, которые, наоборот, выполняются по умолчанию – например, фаза compile. К ней по умолчанию привязан свой плагин и goal, как уже упоминалось выше.

Узнать, что именно происходит при сборке, можно, например, запустив сборку – все goals выведутся в консоль.

Можно также вывести все goals данной фазы так:

mvn help:describe -Dcmd=<фаза>

Попробуем запросить все goal фазы compile:

mvn help:describe -Dcmd=compile

Ответ такой:

compile' is a phase corresponding to this plugin:
org.apache.maven.plugins:maven-compiler-plugin:3.6:compile

То есть на фазе compile по умолчанию выполняется maven-compiler-plugin. Через двоеточие указана goal, она называется compile.

Apache Maven Help Plugin

The Maven Help Plugin is used to get relative information about a project or the system. It can be used to get a description of a particular plugin, including the plugin’s goals with their parameters and component requirements, the effective POM and effective settings of the current build, and the profiles applied to the current project being built.

Goals Overview

The Help Plugin has 7 goals:

  • help:active-profiles lists the profiles which are currently active for the build.
  • help:all-profiles lists the available profiles under the current project.
  • help:describe describes the attributes of a Plugin and/or a Mojo (Maven plain Old Java Object).
  • help:effective-pom displays the effective POM as an XML for the current build, with the active profiles factored in. If verbose, a comment is added to each XML element describing the origin of the line.
  • help:effective-settings displays the calculated settings as an XML for the project, given any profile enhancement and the inheritance of the global settings into the user-level settings.
  • help:evaluate evaluates Maven expressions given by the user in an interactive mode.
  • help:system displays a list of the platform details like system properties and environment variables.

Major Version Upgrade to version 3.0.0

Please note that the goal expressions has been completely removed from the plugin. All the Maven expressions that are supported as plugin parameters are available in the Javadoc of the PluginParameterExpressionEvaluator class.

Usage

General instructions on how to use the Help Plugin can be found on the usage page. Some more specific use cases are described in the examples given below. Last but not least, users occasionally contribute additional examples, tips or errata to the plugin’s wiki page.

If you feel like the plugin is missing a feature or has a defect, you can fill 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

To provide you with better understanding on some usages of the Help Plugin, you can take a look into the following example(s):

Configuring Describe Goal

Default build lifecycle

Запустим сборку, указав фазу install:

mvn install

Обратите внимание, что pom.xml практически пустой – в нем не перечислены никакие фазы и goals, они все привязаны по умолчанию к сборке jar-файла:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>ru.sysout</groupId>
	<artifactId>example-maven-project</artifactId>
	<version>1.0</version>
</project>

При этом в pom.xml даже не указано, что надо собрать jar-файл – этот формат также подразумевается по умолчанию.

Вывод в консоль показывает, какие плагины и голы выполняются при сборке:

 --- maven-resources-plugin:2.6:resources (default-resources) @ example-maven-project ---
 Using platform encoding (Cp1251 actually) to copy filtered resources, i.e. build is platform dependent!
 Copying 0 resource
 
 --- maven-compiler-plugin:3.1:compile (default-compile) @ example-maven-project ---
 Nothing to compile - all classes are up to date
 
 --- maven-resources-plugin:2.6:testResources (default-testResources) @ example-maven-project ---
 Using platform encoding (Cp1251 actually) to copy filtered resources, i.e. build is platform dependent!
 skip non existing resourceDirectory C:\Code\sysout\example-maven-project\src\test\resources
 
 --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ example-maven-project ---
 No sources to compile
 
 --- maven-surefire-plugin:2.12.4:test (default-test) @ example-maven-project ---
 
 --- maven-jar-plugin:2.4:jar (default-jar) @ example-maven-project ---
 Building jar: C:\Code\sysout\example-maven-project\target\example-maven-project-1.0.jar
 
 --- maven-install-plugin:2.4:install (default-install) @ example-maven-project ---
 Installing C:\...\.m2\repository\ru\sysout\example-maven-project\1.0\example-maven-project-1.0.jar
 Installing C:\...\.m2\repository\ru\sysout\example-maven-project\1.0\example-maven-project-1.0.pom
 ------------------------------------------------------------------------
 BUILD SUCCESS

Как видно, по очереди выполняется:

  • копирование папки ресурсов main\resources
  • компиляция исходников из папки main\java
  • копирование тестовых ресурсов test\resources
  • компиляция исходников из папки test\java
  • далее происходит выполнение тестов
  • упаковка в jar и
  • копирование jar файла в .m2 папку на локальном компьютере.

Есть в жизненном цикле еще фаза deploy – развертывание на сервер, эта последняя фаза тут не выполнялась.

Жизненный цикл (lifecycle) сборки – это последовательность фаз (phases).

Выполнение предыдущих фаз

Обратите внимание, что мы указали одну фазу install, но выполняется целый жизненный цикл со всеми предыдущими фазами, фаза install в этом цикле последняя. Чтобы только скопировать ресурсы и скомпилировать проект, выполняем:

Чтобы только скопировать ресурсы и скомпилировать проект, выполняем:

mvn compile

Чтобы, помимо этого, выполнить тесты и  упаковать  проект в jar, выполняем:

mvn package

(при этом выполнится компиляция и другие предваряющие package фазы).

Чтобы развернуть проект на сервере, выполним:

mvn deploy

Все предыдущие фазы, включая install, также при этом выполнятся. В pom.xml при этом должна быть указана конфигурация с данными сервера, куда деплоить проект.

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

Попробуем добавить свое действие к двум фазам.

Maven JXR Plugin

The JXR Plugin produces a cross-reference of the project’s sources. The generated reports make it easier for the user to reference or find specific lines of code. It is also handy when used with the PMD Plugin for referencing errors found in the code.

Goals Overview

The JXR Plugin has 6 goals:

  • jxr:jxr is used to generate a cross-reference page of the project’s main sources. The generated JXR files can be linked to the javadocs of the project.
  • jxr:jxr-nofork is used to generate a cross-reference page of the project’s main sources without forking the generate-sources phase again. Note that this goal does require generation of main sources before site generation, e.g. by invoking mvn clean deploy site.
  • jxr:aggregate is used to generate an aggregated cross-reference page of the project’s main sources. The generated JXR files can be linked to the javadocs of the project.
  • jxr:test-jxr on the other hand, is used to generate a cross-reference page of the project’s test sources.
  • jxr:test-jxr-nofork on the other hand, is used to generate a cross-reference page of the project’s test sources. without forking the generate-test-sources phase again. Note that this goal does require generation of test sources before site generation, e.g. by invoking mvn clean deploy site.
  • jxr:test-aggregate on the other hand, is used to generate an aggregated cross-reference page of the project’s test sources.

Usage

General instructions on how to use the JXR Plugin can be found on the usage page. Some more specific use cases are described in the examples given below. Last but not least, users occasionally contribute additional examples, tips or errata to the plugin’s wiki page.

If you feel like the plugin is missing a feature or has a defect, you can fill 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

To provide you with better understanding on some usages of the JXR Plugin, you can take a look into the following examples:

  • Aggregating JXR Reports for Multi-Projects
  • Linking JXR Files to Javadocs
  • Generate JXR without duplicate execution of phase generate-sources

Описание Maven

Maven — один из самых популярных сборщиков для Java. Для чего его можно использовать:

  1. Сборка Java проекта с подтягиванием зависимостей.
  2. Создание jar.
  3. Автоматически сгенерировать сопроводительную документации для кода на основе комментариев.
  4. Создание дистрибутива.

Если проект java достаточно простой, можно собрать его вручную в командной строке. При больших объемах проекта такую команду записывают в bat/sh скрипт.

Структура проекта описывается через файл pom.xml (POM — Project Object Model), он должен лежать в корневой папке проекта.

Главным объектом Maven является артефакт (любая библиотека, хранящаяся в репозитории, зависимости и плагины).

Зависимости — это библиотеки, используемые в проекте для компиляции кода или его тестирования.

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

Архетип — стандартная организация файлов и каталогов, используемая в разных проектах (веб, swing-проекты, тесты). То есть Maven знает как обычно строятся проекты разных видов и в соответствии с выбранным архетипом создает структуру файлов и каталогов.

Название артефакта состоит из названия группы, собственного названия и версии. Например, Spring в среде Maven будет иметь название:

org.springframework.spring:2.5.5.

Последний домен — artifactId, все что перед ним — groupId.

Multi Module Setup

So now let us take a look into a situation where we have a multi module build. We have a parent pom and one or more children. The parent pom will look like this:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache</groupId>
    <artifactId>apache</artifactId>
    <version>18</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-parent</artifactId>
  <name>First CI Friendly</name>
  <version>${revision}</version>
  ...
  <properties>
    <revision>1.0.0-SNAPSHOT</revision>
  </properties>
  <modules>
    <module>child1</module>
    ..
  </modules>
</project>

The child will look like this:

<project>
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.maven.ci</groupId>
    <artifactId>ci-parent</artifactId>
    <version>${revision}</version>
  </parent>
  <groupId>org.apache.maven.ci</groupId>
  <artifactId>ci-child</artifactId>
   ...
</project>

Apache Maven Assembly Plugin

Introduction

The Assembly Plugin for Maven enables developers to combine project output into a single distributable archive that also contains dependencies, modules, site documentation, and other files.

Your project can easily build distribution «assemblies» using one of the prefabricated assembly descriptors. These descriptors handle many common operations, such as packaging a project’s artifact along with generated documentation into a . Alternatively, your project can provide its own descriptor and assume a much higher level of control over how dependencies, modules, file-sets, and individual files are packaged in the assembly.

Currently it can create distributions in the following formats:

  • zip
  • tar
  • tar.gz (or tgz)
  • tar.bz2 (or tbz2)
  • tar.snappy
  • tar.xz (or txz)
  • jar
  • dir
  • war
  • and any other format that the ArchiveManager has been configured for

If your project wants to package your artifact in an uber-jar, the assembly plugin provides only basic support. For more control, use the Maven Shade Plugin.

To use the Assembly Plugin in Maven, you simply need to:

  • choose or write the assembly descriptor to use,
  • configure the Assembly Plugin in your project’s pom.xml, and
  • run «mvn assembly:single» on your project.

To write your own custom assembly, you will need to refer to the Assembly Descriptor Format reference.

What is an Assembly?

An «assembly» is a group of files, directories, and dependencies that are assembled into an archive format and distributed. For example, assume that a Maven project defines a single JAR artifact that contains both a console application and a Swing application. Such a project could define two «assemblies» that bundle the application with a different set of supporting scripts and dependency sets. One assembly would be the assembly for the console application, and the other assembly could be a Swing application bundled with a slightly different set of dependencies.

The Assembly Plugin provides a descriptor format which allows you to define an arbitrary assembly of files and directories from a project. For example, if your Maven project contains the directory «src/main/bin», you can instruct the Assembly Plugin to copy the contents of this directory to the «bin» directory of an assembly and to change the permissions of the files in the «bin» directory to UNIX mode 755. The parameters for configuring this behavior are supplied to the Assembly Plugin by way of the assembly descriptor.

Goals

The main goal in the assembly plugin is the single goal. It is used to create all assemblies.

For more information about the goals that are available in the Assembly Plugin, see the plugin documentation page.

Assembly and Component Descriptor Schemas (XSD)

  • http://maven.apache.org/xsd/assembly-2.0.0.xsd, http://maven.apache.org/xsd/assembly-component-2.0.0.xsd (for version 3.0 and higher)
  • http://maven.apache.org/xsd/assembly-1.1.3.xsd, http://maven.apache.org/xsd/component-1.1.3.xsd (for version 2.5.4 and higher)
  • http://maven.apache.org/xsd/assembly-1.1.2.xsd, http://maven.apache.org/xsd/component-1.1.2.xsd (for version 2.2 and higher)
  • http://maven.apache.org/xsd/assembly-1.1.1.xsd, http://maven.apache.org/xsd/component-1.1.1.xsd (for version 2.2-beta-4 — 2.2-beta-5)
  • http://maven.apache.org/xsd/assembly-1.1.0.xsd, http://maven.apache.org/xsd/component-1.1.0.xsd (for version 2.2-beta-1 — 2.2-beta-3)
  • http://maven.apache.org/xsd/assembly-1.0.0.xsd, http://maven.apache.org/xsd/component-1.0.0.xsd (for version 2.1 and lower)

Usage

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

If you feel like the plugin is missing a feature or has a defect, you can fill 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

To provide you with better understanding on some usages of the Assembly Plugin, you can take a look into the examples which can be found here.

Зависимости и репозитории.

Большинство популярных библиотек находятся в центральном репозитории , поэтому их можно сразу прописывать в раздел dependencies pom-файла.

Например, чтобы подключить Spring Framework нужно определить зависимость:

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifacrId>spring</artifactId>

<version>2.5.5</version>

</dependency>

</dependencies>

Можно не указывать версию, тогда Maven возьмет последний вариант, но рекомендуется это делать.

Специфические вещи не находятся в центральном репозитории и нужно в таких случаях указать репозиторий вручную. К примеру, добавим зависимость JSF-фреймворка ajax-компонентов JBoss RichFaces.

С зависимостями все просто:

<dependencies>

<dependency>

<groupId>org.richfaces.ui>/groupId>

<artifactId>richfaces-ui</artifactId>

<version>3.3.1.GA</version>

</dependency>

</dependencies>

А репозиторий JBoss нужно прописать вручную либо в файле setting.xml в корне локального репозитория, либо в pom.xml, в зависимости от того, нужен ли этот репозиторий во всех проектах или в одном конкретном:

<!— JBoss RichFaces Repository —> <repositories> <repository> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> <updatePolicy>never</updatePolicy> </snapshots> <id>repository.jboss.com</id> <name>Jboss Repository for Maven</name> <url> </url> <layout>default</layout> </repository> </repositories>

Обычно на сайтах крупных проектов пишут все что нужно для встраивания их библиотеки в проект на основе Maven.

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

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

Adblock
detector