Relativepath maven что это
Relativepath maven что это
Introduction to the POM
What is a POM?
A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target ; the source directory, which is src/main/java ; the test source directory, which is src/test/java ; and so on. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.
Some of the configuration that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified.
Super POM
The Super POM is Maven’s default POM. All POMs extend the Super POM unless explicitly set, meaning the configuration specified in the Super POM is inherited by the POMs you created for your projects.
You can see the Super POM for Maven 3.6.3 in Maven Core reference documentation.
Minimal POM
The minimum requirement for a POM are the following:
Also, as mentioned in the first section, if the configuration details are not specified, Maven will use their defaults. One of these default values is the packaging type. Every Maven project has a packaging type. If it is not specified in the POM, then the default value «jar» would be used.
Furthermore, you can see that in the minimal POM the repositories were not specified. If you build your project using the minimal POM, it would inherit the repositories configuration in the Super POM. Therefore when Maven sees the dependencies in the minimal POM, it would know that these dependencies will be downloaded from https://repo.maven.apache.org/maven2 which was specified in the Super POM.
Project Inheritance
Elements in the POM that are merged are the following:
The Super POM is one example of project inheritance, however you can also introduce your own parent POMs by specifying the parent element in the POM, as demonstrated in the following examples.
Example 1
The Scenario
As an example, let us reuse our previous artifact, com.mycompany.app:my-app:1. And let us introduce another artifact, com.mycompany.app:my-module:1.
And let us specify their directory structure as the following:
Note: my-module/pom.xml is the POM of com.mycompany.app:my-module:1 while pom.xml is the POM of com.mycompany.app:my-app:1
The Solution
Now, if we were to turn com.mycompany.app:my-app:1 into a parent artifact of com.mycompany.app:my-module:1,we will have to modify com.mycompany.app:my-module:1’s POM to the following configuration:
Notice that we now have an added section, the parent section. This section allows us to specify which artifact is the parent of our POM. And we do so by specifying the fully qualified artifact name of the parent POM. With this setup, our module can now inherit some of the properties of our parent POM.
Alternatively, if you want the groupId or the version of your modules to be the same as their parents, you can remove the groupId or the version identity of your module in its POM.
This allows the module to inherit the groupId or the version of its parent POM.
Example 2
The Scenario
However, that would work if the parent project was already installed in our local repository or was in that specific directory structure (parent pom.xml is one directory higher than that of the module’s pom.xml ).
But what if the parent is not yet installed and if the directory structure is as in the following example?
The Solution
To address this directory structure (or any other directory structure), we would have to add the element to our parent section.
Project Aggregation
Project Aggregation is similar to Project Inheritance. But instead of specifying the parent POM from the module, it specifies the modules from the parent POM. By doing so, the parent project now knows its modules, and if a Maven command is invoked against the parent project, that Maven command will then be executed to the parent’s modules as well. To do Project Aggregation, you must do the following:
Example 3
The Scenario
Given the previous original artifact POMs and directory structure:
The Solution
If we are to aggregate my-module into my-app, we would only have to modify my-app.
Now, whenever a Maven command processes com.mycompany.app:my-app:1, that same Maven command would be ran against com.mycompany.app:my-module:1 as well. Furthermore, some commands (goals specifically) handle project aggregation differently.
Example 4
The Scenario
But what if we change the directory structure to the following:
How would the parent POM specify its modules?
The Solution
Project Inheritance vs Project Aggregation
If you have several Maven projects, and they all have similar configurations, you can refactor your projects by pulling out those similar configurations and making a parent project. Thus, all you have to do is to let your Maven projects inherit that parent project, and those configurations would then be applied to all of them.
And if you have a group of projects that are built or processed together, you can create a parent project and have that parent project declare those projects as its modules. By doing so, you’d only have to build the parent and the rest will follow.
But of course, you can have both Project Inheritance and Project Aggregation. Meaning, you can have your modules specify a parent project, and at the same time, have that parent project specify those Maven projects as its modules. You’d just have to apply all three rules:
Example 5
The Scenario
Given the previous original artifact POMs again,
Идеальный мавен. Часть 2: структура проекта
Это вторая статья, посвященная мавену и его использованию для организации моих проектов. Целью этой статьи будет структура проекта под управлением мавен. Особых откровений вы не найдёте, скорее набор общих правил для моих проектов. Первую статью можно прочитать здесь.
Структура проекта
Как я уже сказал, я не буду описывать здесь типовую структуру проекта на мавен – вы её знаете или легко можете найти по ссылке: Standard Directory Layout. В этой части я остановлюсь на особенностях, которые я применяю в своих проектах, итак:
Модули
Практически любой мой проект имеет несколько модулей. Практика показывает, что, когда необходимо добавить еще один модуль в проект это гораздо проще сделать в случае изначально модульного проекта. В моих проектах существует 3 типа «модулей» – POM (всегда один), несколько девелоперских модулей с кодом и BOM – если дев. модулей больше одного. В принципе POM это не модуль в понимании мавен, но я всегда оформляю его почти как «модуль» (покажу ниже). В итоге получается, что-то вроде такого:
Проектный POM
Начнём с проектного POM‘а. Я практически всегда убираю его в отдельный каталог с именем pom. Делаю я так по нескольким причинам:
Проектный POM содержит ссылку на супер POM, список модулей, версии проектов от которых он зависит (не библиотек третьих стран, а именно проектов, которые находятся параллельно в разработке в этой компании) и определение версии для модулей и проектов (dependencyManagement). Вот типичный POM для маленького проекта:
В этом примере:
версия проекта, от которого он зависит
и определение версии для модулей и проектов
Зачем это нужно? Что бы полностью исключить использование версий в девелоперских модулях. С такой конфигурацией все версии фиксируются в супер POM‘е (для внешних библиотек) и в проектных POM‘ах (для самого проекта и его зависимостей на внутренние проекты). Это не только делает POM‘ы в модулях чище, но и необходимо для того релиз процесса, который я использую.
BOM POM
Модуль с кодом
Самый примитивный POM. Включает в себя ссылку на проектный POM, artefactId, список зависимостей без версий. При необходимости секцию build c ссылками на плагины. Версия и groupId наследуются из родительского POM’а.
Пример:
Имя артефакта
groupId это имя пакета в Java для этого проекта – в последнее время это стало практически стандартом. С artifactId – немного чудесатей, для своих проектов я всегда беру имя группы плюс имя модуля, что-то вроде этого:
Почему? Имя у итогового артефакта должно быть уникальным (слишком часто все сваливают в один каталог), саму идею я вынес и мира eclipse — так там именуются плагины. Поначалу непривычно, но оно достаточно уникально, придумать его очень просто, увидев в каталоге по имени очень быстро можно найти артефакт в репозитории и source control‘е.
Следовать этой конвенции с именами не обязательно. Главное, это уникальность имени итогового артефакта.
Maven: неразрешимый родительский POM
У меня мой проект maven настроен как 1 проект оболочки и 4 дочерних модуля. Когда я пытаюсь построить оболочку. Я получил:
Если я пытаюсь создать одинокий модуль, я получаю ту же ошибку, только заменяю модуль1, каким бы модулем он ни был.
Пусть все они ссылаются на родителей в своих пометках.
Вот соответствующие части помпона:
сработало для меня.
Просто для справки.
Это также можно исправить, поместив правильный settings.xml файл в
В моем случае проблема была еще более сложной из-за Eclipse: репозиторий был активен только в специальном профиле (
Решением было временно объявить репозиторий вне профиля (безоговорочно), запустить Alt+F5 Maven Update Project, активировать профиль и вернуть объявление репозитория в профиль. Это скорее ошибка Eclipse, а не ошибка Maven.
Неразрешаемый родительский POM: это означает, что вы не можете разрешить родительский репо.
Транг в режиме отладки:
Поскольку родительский репо не является частью центра maven. Решение состоит в том, чтобы указать файл setting.xml в
m2 /, чтобы помочь создать родительский POM. /Users/username/.m2/settings.xml
В этом XML вам может потребоваться указать информацию о репозитории.
Просто добавьте так, чтобы родительский элемент в pom выглядел так:
проверьте, есть ли у вас правильные значения в дочерних POM
В Eclipse, например, вы можете искать его:
Если вы строите в рамках дочернего проекта, это может помочь вам разрешить родительский pom.
установить родительский pom
Но если вы создадите дочерний проект из его папки, это не сработает. Вы можете install сначала поместить родительский pom в свой локальный репозиторий, а затем построить дочерний проект.
Relativepath maven что это
An XSD is available at:
project
element is the root of the descriptor. The following table lists all of the possible child elements.
parent
element contains information required to locate the parent project from which this project will inherit from. Note: The children of this element are not interpolated and must be given as literal values.
Element | Type | Description |
---|---|---|
artifactId | String | The artifact id of the parent project to inherit from. |
groupId | String | The group id of the parent project to inherit from. |
version | String | The version of the parent project to inherit. |
relativePath | String | The relative path of the parent pom.xml file within the check out. If not specified, it defaults to ../pom.xml. Maven looks for the parent POM first in this location on the filesystem, then the local repository, and lastly in the remote repo. relativePath allows you to select a different location, for example when your structure is flat, or deeper without an intermediate parent POM. However, the group ID, artifact ID and version are still required, and must match the file in the location given or it will revert to the repository for the POM. This feature is only for enhancing the development in a local checkout of that project. Set the value to an empty string in case you want to disable the feature and always resolve the parent POM from the repositories. Default value is: ../pom.xml. |
organization
Specifies the organization that produces this project.
Element | Type | Description |
---|---|---|
name | String | The full name of the organization. |
url | String | The URL to the organization’s home page. |
license
Describes the licenses for this project. This is used to generate the license page of the project’s web site, as well as being taken into consideration in other reporting and validation. The licenses listed for the project are that of the project itself, and not of dependencies.
Element | Type | Description |
---|---|---|
name | String | The full legal name of the license. |
url | String | The official url for the license text. |
distribution | String | The primary method by which this project may be distributed. repo may be downloaded from the Maven repository manual user must manually download and install the dependency. |
comments | String | Addendum information pertaining to this license. |
developer
Information about one of the committers on this project.
contributor
Description of a person who has contributed to the project, but who does not have commit privileges. Usually, these contributions come in the form of patches submitted.
mailingList
This element describes all of the mailing lists associated with a project. The auto-generated site references this information.
Element | Type | Description |
---|---|---|
name | String | The name of the mailing list. |
subscribe | String | The email address or link that can be used to subscribe to the mailing list. If this is an email address, a mailto: link will automatically be created when the documentation is created. |
unsubscribe | String | The email address or link that can be used to unsubscribe to the mailing list. If this is an email address, a mailto: link will automatically be created when the documentation is created. |
post | String | The email address or link that can be used to post to the mailing list. If this is an email address, a mailto: link will automatically be created when the documentation is created. |
archive | String | The link to a URL where you can browse the mailing list archive. |
otherArchives/otherArchive* | List | (Many) The link to alternate URLs where you can browse the list archive. |
prerequisites
Describes the prerequisites a project can have.
Element | Type | Description |
---|---|---|
maven | String | The minimum version of Maven required to build the project, or to use this plugin. Default value is: 2.0. |
The element contains informations required to the SCM (Source Control Management) of the project.
Element | Type | Description |
---|---|---|
connection | String | The source control management system URL that describes the repository and how to connect to the repository. For more information, see the URL format and list of supported SCMs. This connection is read-only. |
developerConnection | String | Just like connection, but for developers, i.e. this scm connection will not be read only. |
tag | String | The tag of current code. By default, it’s set to HEAD during development. Default value is: HEAD. |
url | String | The URL to the project’s browsable SCM repository, such as ViewVC or Fisheye. |
issueManagement
Information about the issue tracking (or bug tracking) system used to manage this project.
Element | Type | Description |
---|---|---|
system | String | The name of the issue management system, e.g. Bugzilla |
url | String | URL for the issue management system used by the project. |
ciManagement
The element contains informations required to the continuous integration system of the project.
Element | Type | Description |
---|---|---|
system | String | The name of the continuous integration system, e.g. continuum. |
url | String | URL for the continuous integration system used by the project if it has a web interface. |
notifiers/notifier* | List | (Many) Configuration for notifying developers/users when a build is unsuccessful, including user information and notification mode. |
notifier
Configures one method for notifying users/developers when a build breaks.
distributionManagement
This elements describes all that pertains to distribution for a project. It is primarily used for deployment of artifacts and the site produced by the build.
Element | Type | Description |
---|---|---|
repository | DeploymentRepository | Information needed to deploy the artifacts generated by the project to a remote repository. |
snapshotRepository | DeploymentRepository | Where to deploy snapshots of artifacts to. If not given, it defaults to the repository element. |
site | Site | Information needed for deploying the web site of the project. |
downloadUrl | String | The URL of the project’s download page. If not given users will be referred to the homepage given by url. This is given to assist in locating artifacts that are not in the repository due to licensing restrictions. |
relocation | Relocation | Relocation information of the artifact if it has been moved to a new group ID and/or artifact ID. |
status | String | Gives the status of this artifact in the remote repository. This must not be set in your local project, as it is updated by tools placing it in the reposiory. Valid values are: none (default), converted (repository manager converted this from an Maven 1 POM), partner (directly synced from a partner Maven 2 repository), deployed (was deployed from a Maven 2 instance), verified (has been hand verified as correct and final). |
repository
Repository contains the information needed for deploying to the remote repository.
releases
snapshots
snapshotRepository
Repository contains the information needed for deploying to the remote repository.
Contains the information needed for deploying websites.
Element | Type | Description |
---|---|---|
id | String | A unique identifier for a deployment location. This is used to match the site to configuration in the settings.xml file, for example. |
name | String | Human readable name of the deployment location. |
url | String | The url of the location where website is deployed, in the form protocol://hostname/path. |
relocation
Describes where an artifact has moved to. If any of the values are omitted, it is assumed to be the same as it was before.
Element | Type | Description |
---|---|---|
groupId | String | The group ID the artifact has moved to. |
artifactId | String | The new artifact ID of the artifact. |
version | String | The new version of the artifact. |
message | String | An additional message to show the user about the move, such as the reason. |
dependencyManagement
Section for management of default dependency information for use in a group of POMs.
Element | Type | Description |
---|---|---|
dependencies/dependency* | List | (Many) The dependencies specified here are not used until they are referenced in a POM within the group. This allows the specification of a «standard» version for a particular dependency. |
dependency
The element contains information about a dependency of the project.
exclusion
The element contains informations required to exclude an artifact to the project.
Element | Type | Description |
---|---|---|
artifactId | String | The artifact ID of the project to exclude. |
groupId | String | The group ID of the project to exclude. |
repository
A repository contains the information needed for establishing connections with remote repository.
pluginRepository
A repository contains the information needed for establishing connections with remote repository.
build
The element contains informations required to build the project.
extension
Describes a build extension to utilise.
Element | Type | Description |
---|---|---|
groupId | String | The group ID of the extension’s artifact. |
artifactId | String | The artifact ID of the extension. |
version | String | The version of the extension. |
resource
This element describes all of the classpath resources associated with a project or unit tests.
Element | Type | Description |
---|---|---|
targetPath | String | Describe the resource target path. The path is relative to the target/classes directory (i.e. $ ). For example, if you want that resource to appear in a specific package (org.apache.maven.messages), you must specify this element with this value: org/apache/maven/messages. This is not required if you simply put the resources in that directory structure at the source, however. |
filtering | String | Whether resources are filtered to replace tokens with parameterised values or not. The values are taken from the properties element and from the properties in the files listed in the filters element. Note: While the type of this field is String for technical reasons, the semantic type is actually Boolean. Default value is false. |
mergeId | String | FOR INTERNAL USE ONLY. This is a unique identifier assigned to each resource to allow Maven to merge changes to this resource that take place during the execution of a plugin. This field must be managed by the generated parser and formatter classes in order to allow it to survive model interpolation. |
directory | String | Describe the directory where the resources are stored. The path is relative to the POM. |
includes/include* | List | (Many) A list of patterns to include, e.g. **/*.xml. |
excludes/exclude* | List | (Many) A list of patterns to exclude, e.g. **/*.xml |
testResource
This element describes all of the classpath resources associated with a project or unit tests.
Element | Type | Description |
---|---|---|
targetPath | String | Describe the resource target path. The path is relative to the target/classes directory (i.e. $ ). For example, if you want that resource to appear in a specific package (org.apache.maven.messages), you must specify this element with this value: org/apache/maven/messages. This is not required if you simply put the resources in that directory structure at the source, however. |
filtering | String | Whether resources are filtered to replace tokens with parameterised values or not. The values are taken from the properties element and from the properties in the files listed in the filters element. Note: While the type of this field is String for technical reasons, the semantic type is actually Boolean. Default value is false. |
mergeId | String | FOR INTERNAL USE ONLY. This is a unique identifier assigned to each resource to allow Maven to merge changes to this resource that take place during the execution of a plugin. This field must be managed by the generated parser and formatter classes in order to allow it to survive model interpolation. |
directory | String | Describe the directory where the resources are stored. The path is relative to the POM. |
includes/include* | List | (Many) A list of patterns to include, e.g. **/*.xml. |
excludes/exclude* | List | (Many) A list of patterns to exclude, e.g. **/*.xml |
pluginManagement
Section for management of default plugin information for use in a group of POMs.
Element | Type | Description |
---|---|---|
plugins/plugin* | List | (Many) The list of plugins to use. |
plugin
element contains informations required for a plugin.
Element | Type | Description |
---|---|---|
groupId | String | The group ID of the plugin in the repository. Default value is: org.apache.maven.plugins. |
artifactId | String | The artifact ID of the plugin in the repository. |
version | String | The version (or valid range of versions) of the plugin to be used. |
extensions | String | Whether to load Maven extensions (such as packaging and type handlers) from this plugin. For performance reasons, this should only be enabled when necessary. Note: While the type of this field is String for technical reasons, the semantic type is actually Boolean. Default value is false. |
executions/execution* | List | (Many) Multiple specifications of a set of goals to execute during the build lifecycle, each having (possibly) a different configuration. |
dependencies/dependency* | List | (Many) Additional dependencies that this project needs to introduce to the plugin's classloader. |
goals | DOM | Deprecated. Unused by Maven. |
inherited | String | Whether any configuration should be propagated to child POMs. Note: While the type of this field is String for technical reasons, the semantic type is actually Boolean. Default value is true. |
configuration | DOM | The configuration as DOM object. |
execution
The element contains informations required for the execution of a plugin.
Element | Type | Description |
---|---|---|
id | String | The identifier of this execution for labelling the goals during the build, and for matching executions to merge during inheritance and profile injection. Default value is: default. |
phase | String | The build lifecycle phase to bind the goals in this execution to. If omitted, the goals will be bound to the default phase specified in their metadata. |
goals/goal* | List | (Many) The goals to execute with the given configuration. |
inherited | String | Whether any configuration should be propagated to child POMs. Note: While the type of this field is String for technical reasons, the semantic type is actually Boolean. Default value is true. |
configuration | DOM | The configuration as DOM object. |
reporting
Section for management of reports and their configuration.
plugin
element contains informations required for a report plugin.
Element | Type | Description |
---|---|---|
groupId | String | The group ID of the reporting plugin in the repository. Default value is: org.apache.maven.plugins. |
artifactId | String | The artifact ID of the reporting plugin in the repository. |
version | String | The version of the reporting plugin to be used. |
inherited | String | Whether the configuration in this plugin should be made available to projects that inherit from this one. Note: While the type of this field is String for technical reasons, the semantic type is actually Boolean. Default value is true. |
configuration | DOM | The configuration of the reporting plugin. |
reportSets/reportSet* | List | (Many) Multiple specifications of a set of reports, each having (possibly) different configuration. This is the reporting parallel to an execution in the build. |
reportSet
Represents a set of reports and configuration to be used to generate them.
Element | Type | Description |
---|---|---|
id | String | The unique id for this report set, to be used during POM inheritance and profile injection for merging of report sets. Default value is: default. |
configuration | DOM | Configuration of the report to be used when generating this set. |
inherited | String | Whether any configuration should be propagated to child POMs. |
reports/report* | List | (Many) The list of reports from this plugin which should be generated from this set. |
profile
Modifications to the build process which is activated based on environmental parameters or command line arguments.
activation
The conditions within the build runtime environment which will trigger the automatic inclusion of the build profile.
This is an activator which will detect an operating system's attributes in order to activate its profile.
Element | Type | Description |
---|---|---|
name | String | The name of the operating system to be used to activate the profile. This must be an exact match of the $ Java property, such as Windows XP. |
family | String | The general family of the OS to be used to activate the profile, such as windows or unix. |
arch | String | The architecture of the operating system to be used to activate the profile. |
version | String | The version of the operating system to be used to activate the profile. |
property
This is the property specification used to activate a profile. If the value field is empty, then the existence of the named property will activate the profile, otherwise it does a case-sensitive match against the property value as well.
Element | Type | Description |
---|---|---|
name | String | The name of the property to be used to activate a profile. |
value | String | The value of the property required to activate a profile. |
This is the file specification used to activate the profile. The missing value will be the location of a file that needs to exist, and if it doesn't the profile will be activated. On the other hand exists will test for the existence of the file and if it is there the profile will be activated.