Maven settings xml где находится
- Apache /
- Maven /
- Settings Reference
- | Last Published: 2023-10-26
- | Get Sources
- Download
Settings Reference
Introduction
Quick Overview
The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml , but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information.
There are two locations where a settings.xml file may live:
- The Maven install: $/conf/settings.xml
- A user’s install: $/.m2/settings.xml
The former settings.xml are also called global settings, the latter settings.xml are referred to as user settings. If both files exists, their contents gets merged, with the user-specific settings.xml being dominant.
Tip: If you need to create user-specific settings from scratch, it’s easiest to copy the global settings from your Maven installation to your $/.m2 directory. Maven’s default settings.xml is a template with comments and examples so you can quickly tweak it to match your needs.
Here is an overview of the top elements under settings :
The contents of the settings.xml can be interpolated using the following expressions:
- $ and all other system properties (since Maven 3.0)
- $ etc. for environment variables
Note that properties defined in profiles within the settings.xml cannot be used for interpolation.
Settings Details
Simple Values
Half of the top-level settings elements are simple values, representing a range of values which describe elements of the build system that are active full-time.
$/.m2/repository true false .
- localRepository: This value is the path of this build system’s local repository. The default value is $/.m2/repository . This element is especially useful for a main build server allowing all logged-in users to build from a common local repository.
- interactiveMode: true if Maven should attempt to interact with the user for input, false if not. Defaults to true .
- offline: true if this build system should operate in offline mode, defaults to false . This element is useful for build servers which cannot connect to a remote repository, either because of network setup or security reasons.
Plugin Groups
This element contains a list of pluginGroup elements, each contains a groupId. The list is searched when a plugin is used and the groupId is not provided in the command line. This list automatically contains org.apache.maven.plugins and org.codehaus.mojo .
. org.eclipse.jetty .
For example, given the above settings the Maven command line may execute org.eclipse.jetty:jetty-maven-plugin:run with the truncated command:
mvn jetty:run
Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml . This type of information should exist on the build server in the settings.xml .
. server001 my_login my_password $/.ssh/id_dsa some_passphrase 664 775 .
- id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.
- username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.
- privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is $/.ssh/id_dsa ) and a passphrase , if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.
- filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corresponding to *nix file permissions, e.g. 664, or 775.
Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.
Password Encryption
A new feature — server password and passphrase encryption has been added to 2.1.0+. See details on this page
Mirrors
. planetmirror.com PlanetMirror Australia http://downloads.planetmirror.com/pub/maven2 central .
- id, name: The unique identifier and user-friendly name of this mirror. The id is used to differentiate between mirror elements and to pick the corresponding credentials from the section when connecting to the mirror.
- url: The base URL of this mirror. The build system will use this URL to connect to a repository rather than the original repository URL.
- mirrorOf: The id of the repository that this is a mirror of. For example, to point to a mirror of the Maven central repository ( https://repo.maven.apache.org/maven2/ ), set this element to central . More advanced mappings like repo1,repo2 or *,!inhouse are also possible. This must not match the mirror id .
For a more in-depth introduction of mirrors, please read the Guide to Mirror Settings.
Proxies
. myproxy true http proxy.somewhere.com 8080 proxyuser somepassword *.google.com|ibiblio.org .
- id: The unique identifier for this proxy. This is used to differentiate between proxy elements.
- active: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.
- protocol, host, port: The protocol://host:port of the proxy, separated into discrete elements.
- username, password: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.
- nonProxyHosts: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited — comma delimited is also common.
Profiles
The profile element in the settings.xml is a truncated version of the pom.xml profile element. It consists of the activation , repositories , pluginRepositories and properties elements. The profile elements only include these four elements because they concerns themselves with the build system as a whole (which is the role of the settings.xml file), not about individual project object model settings.
If a profile is active from settings , its values will override any equivalently ID’d profiles in a POM or profiles.xml file.
Activation
Activations are the key of a profile. Like the POM’s profiles, the power of a profile comes from its ability to modify some values only under certain circumstances; those circumstances are specified via an activation element.
. test false 1.5 Windows XP Windows x86 5.1.2600 mavenVersion 2.0.3 $/file2.properties $/file1.properties . .
Activation occurs when all specified criteria have been met, though not all are required at once.
- jdk: activation has a built in, Java-centric check in the jdk element. This will activate if the test is run under a jdk version number that matches the prefix given. In the above example, 1.5.0_06 will match. Ranges are also supported. See the maven-enforcer-plugin for more details about supported ranges.
- os: The os element can define some operating system specific properties shown above. See the maven-enforcer-plugin for more details about OS values.
- property: The profile will activate if Maven detects a property (a value which can be dereferenced within the POM by $ ) of the corresponding name=value pair.
- file: Finally, a given filename may activate the profile by the existence of a file, or if it is missing .
The activation element is not the only way that a profile may be activated. The settings.xml file’s activeProfile element may contain the profile’s id . They may also be activated explicitly through the command line via a comma separated list after the -P flag (e.g. -P test ).
To see which profile will activate in a certain build, use the maven-help-plugin .
mvn help:active-profiles
Properties
Maven properties are value placeholder, like properties in Ant. Their values are accessible anywhere within a POM by using the notation $ , where X is the property. They come in five different styles, all accessible from the settings.xml file:
- env.X : Prefixing a variable with “env.” will return the shell’s environment variable. For example, $ contains the $path environment variable ( %PATH% in Windows).
- project.x : A dot (.) notated path in the POM will contain the corresponding element’s value. For example:
is accessible via $ .1.0 - settings.x : A dot (.) notated path in the settings.xml will contain the corresponding element’s value. For example:
is accessible via $ .false - Java System Properties: All properties accessible via java.lang.System.getProperties() are available as POM properties, such as $ .
- x : Set within a element or an external files, the value may be used as $ .
. . $/our-project . .
The property $ is accessible from a POM if this profile is active.
Repositories
Repositories are remote collections of projects from which Maven uses to populate the local repository of the build system. It is from this local repository that Maven calls it plugins and dependencies. Different remote repositories may contain different projects, and under the active profile they may be searched for a matching release or snapshot artifact.
. . codehausSnapshots Codehaus Snapshots false always warn true never fail http://snapshots.maven.codehaus.org/maven2 default myPluginRepo My Plugins repo true false https://maven-central-eu. com/maven2/ . .
- releases, snapshots: These are the policies for each type of artifact, Release or snapshot. With these two sets, a POM has the power to alter the policies for each type independent of the other within a single repository. For example, one may decide to enable only snapshot downloads, possibly for development purposes.
- enabled: true or false for whether this repository is enabled for the respective type ( releases or snapshots ).
- updatePolicy: This element specifies how often updates should attempt to occur. Maven will compare the local POM’s timestamp (stored in a repository’s maven-metadata file) to the remote. The choices are: always , daily (default), interval:X (where X is an integer in minutes) or never .
- checksumPolicy: When Maven deploys files to the repository, it also deploys corresponding checksum files. Your options are to ignore , fail , or warn on missing or incorrect checksums.
- layout: In the above description of repositories, it was mentioned that they all follow a common layout. This is mostly correct. Maven 2 has a default layout for its repositories; however, Maven 1.x had a different layout. Use this element to specify which if it is default or legacy .
Plugin Repositories
Repositories are home to two major types of artifacts. The first are artifacts that are used as dependencies of other artifacts. These are the majority of artifacts that reside within central. The other type of artifact is plugins. Maven plugins are themselves a special type of artifact. Because of this, plugin repositories may be separated from other repositories (although, I have yet to hear a convincing argument for doing so). In any case, the structure of the pluginRepositories element block is similar to the repositories element. The pluginRepository elements each specify a remote location of where Maven can find new plugins.
Active Profiles
. env-test
The final piece of the settings.xml puzzle is the activeProfiles element. This contains a set of activeProfile elements, which each have a value of a profile id . Any profile id defined as an activeProfile will be active, regardless of any environment settings. If no matching profile is found nothing will happen. For example, if env-test is an activeProfile , a profile in a pom.xml (or profile.xml with a corresponding id will be active. If no such profile is found then execution will continue as normal.
Руководство по Maven. Репозитории.
При работе с Maven под репозиторием мы понимаем директорию, где хранятся все JAR, библиотеки, плагины и любые артефакты, которыми Maven может воспользоваться.
Существует три типа репозиториев Maven:
Локальные репозитории
Локальный репозиторий – это директория, которая хранится на нашем компьютере. Она создаётся в момент первого выполнения любой команды Maven.
Локальный репозиторий Maven хранит все зависимости проекта (библиотеки, плагины и т.д.). Когда мы выполняем сборку проекта с помощью Maven, то все зависимости (их JAR-файлы) автоматически загружаются в локальный репозиторий. Это помогает нам избежать использование ссылок на удалённый репозиторий при каждой сборке проекта.
По умолчанию, локальный репозиторий создаётся Maven в директории %USER_HOME%. Для того, чтобы изменить директорию нам необходимо указать её в файле settings.xml, который находится в папке %M2_HOME%\conf.
xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> /home/Documents/MyLocalRepository
Когда мы выполним команду run Maven, то все зависимости будут автоматически загружены в локальный репозиторий.
Центральный репозиторий
Центральный репозиторий Maven – это репозиториий, который обеспечивается сообществом Maven. Он содержит огромное количество часто используемых библиотек.
Если Maven не может найти зависимости в локальном репозитории, то автоматически начинается поиск необходимых файлов в центральном репозитории по этому адресу: http://repo1.maven.org/maven2/.
Удалённый репозиторий
Иногда, Maven не может найти необходимые зависимости в центральном репозитории. В этом случае, процесс сборки прерывается и в консоль выводится сообщение об ошибке.
Для того, чтобы предотвратить подобную ситуацию, в Maven предусмотрен механизм Удалённого репозитория, который является репозиторием, который определяется самим разработчиком. Там могут храниться все необходимые зависимости.
Для того, чтобы настроить удалённый репозиторий, необходимо внести следующие изменения в файл pom.xml.
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"> 4.0.0 com.companyname.projectgroup Tutorials 1.0 net.proselyte.private-lib private-lib 1.0.0 proselyte.lib1 http://download.proselyte.net/maven2/lib1 proselyte.lib2 http://download.proselyte.net/maven2/lib2
Порядок поиска зависимостей Maven
Когда мы выполняем сборку проекта в Maven, автоматически начинается поиск необходимых зависимостей в следующем порядке:
- Поиск зависимостей в локальном репозитории Если зависимости не обнаружены, происходит переход к шагу 2.
- Поиск зависимостей в центральном репозитории. Если они не обнаружены и удалённый репозиторий определён, то происходит переход к шагу 4.
- Если удалённый репозиторий не определён, то процесс сборки прекращается и выводится сообщение об ошибке.
- Поиск зависимостей на удалённом репозитории, если они найдены, то происходит их загрузка в локальный репозиторий, если нет – выводится сообщение об ошибке.
How do I find out which settings.xml file maven is using
I recently changed my password and have to change my maven settings.xml file to reflect that. However, no matter what I do in the settings.xml file, the changed password just won’t get picked up. Out of desperation, I ran maven with the -s switch ( mvn -s
352k 105 105 gold badges 1213 1213 silver badges 991 991 bronze badges
asked Apr 3, 2012 at 7:22
6,860 6 6 gold badges 41 41 silver badges 68 68 bronze badges
Duplicate for stackoverflow.com/questions/1261215/…
Apr 3, 2012 at 7:27
Actually, The other question has no answer that I needed. nico_ekito provided with the answer that I need.
Apr 3, 2012 at 7:38
2 Answers 2
Use the Maven debug option, ie mvn -X :
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100) Maven home: /usr/java/apache-maven-3.0.3 Java version: 1.6.0_12, vendor: Sun Microsystems Inc. Java home: /usr/java/jdk1.6.0_12/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix" [INFO] Error stacktraces are turned on. [DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml [DEBUG] Reading user settings from /home/myhome/.m2/settings.xml .
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml .
Основы Maven: что это такое и как работает
Собираем проект на Java быстро, без регистрации и СМС.
Иллюстрация: Lip Kee / Apache Software Foundation / Wikimedia Commons / John Fowler / Maksym Ostrozhynskyy / Brett Wharton / Ben Kolde / Unsplash / Дима Руденок для Skillbox Media
Богдан Островерхов
Пишет о сетях, инструментах для разработчиков и языках программирования. Любит готовить, играть в инди‑игры и программировать на Python.
Если спросить у Java-разработчика, кто его лучший друг, то, скорее всего, он расскажет про Apache Maven. Это фреймворк для автоматизации сборки проектов на основе описания их структуры в файлах на языке POM (Project Object Model).
Пока что звучит сложно, но в этой статье мы разберёмся в основах работы со сборщиком проектов и заглянем в его сердце — файл pom.xml.
Что вы узнаете про Maven:
- зачем он нужен и есть ли у него аналоги;
- как его правильно установить на компьютер и можно ли обойтись без этого;
- как его настроить и собрать свой первый проект;
- зачем ему репозитории и какими они бывают.
Что такое Maven
Maven — это инструмент для автоматической сборки проектов на Java и других языках программирования. Он помогает разработчикам правильно подключить библиотеки и фреймворки, управлять их версиями, выстроить структуру проекта и составить к нему документацию.
Например, чтобы собрать приложение для управления базами данных на Java, нам понадобятся фреймворки Spring и Hibernate, библиотека JUnit для модульного тестирования и сама база данных. Всё это можно собрать в одном проекте вручную, но могут быть трудности из-за большого числа зависимостей. Здесь на помощь разработчикам приходит Maven. Он автоматически добавит эти или другие зависимости в проект и соберёт его в исполняемый файл.
Maven — не единственный сборщик проектов. Некоторые разработчики используют его аналоги — Gradle и Ant. Но именно Maven сегодня — золотой стандарт в индустрии.
Установка Maven
Maven можно установить вручную или воспользоваться IDE с предустановленным сборщиком. Второй вариант удобнее и быстрее, но начнём мы с обычной установки в операционную систему.
Важно! Чтобы работать с Java, у вас на компьютере должен быть установлен и настроен JDK. Мы уже писали, как это сделать правильно.
Установка Maven вручную
Скачайте архив со сборщиком для своей операционной системы с официального сайта Apache Maven и распакуйте его. Лучше всего создать для этого отдельную папку, так как путь к ней нам понадобится позже.
Если у вас Linux, то установку можно запустить через командную строку:
В открывшемся окне нажмите кнопку Создать и укажите полный адрес до папки bin из распакованного архива Maven:
Проверьте настройку переменных среды. Для этого зайдите в командную строку и введите mvn -v. Если Maven установлен, то появится информация о его версии:
Linux/Mac
Откройте в текстовом редакторе файл ~/.bashrc или ~/.bash_profile в Linux или .zshrc в macOS. Файл находится в домашней директории текущего пользователя . Если файла нет, создайте его и впишите:
Для Mac в последней строке будет указано family: «mac».
Использование Maven в IntelliJ IDEA
Для работы с Maven мы будем использовать IntelliJ IDEA. Это удобная среда разработки, в которой сборщик проектов установлен из коробки.
Настройки Maven в IDE можно найти в правой части рабочей области после создания проекта на Java:
Настройка Maven и сборка проекта
Начнём работу с создания шаблона проекта. Среда разработки и здесь сэкономит нам время, так как самостоятельно пропишет необходимые параметры.
Создайте новый проект:
Программа предложит выбрать Maven Archetype в качестве шаблона сборки. Кликните на него и в окне преднастроек выберите Archetype quickstart. Нажмите Create:
В окне проекта вы увидите, как Maven зашёл в репозитории и начал что-то скачивать, — это нормально:
Слева на экране показана структура проекта. Нам нужен класс App.java, в котором находится метод main. Чтобы найти его, откройте папку src, затем main и java. Внутри App.java хранится небольшой фрагмент кода:
Всё сработало как надо — появился текст Hello World!:
Поздравляем! Вы собрали первый проект в Maven.
Репозитории Maven
Maven умеет не только выводить что-то в консоль. Его мощь — в библиотеках, которые можно подключить к проекту. Для этого используются репозитории.
Репозитории Maven — это хранилища, где находятся библиотеки. Что-то вроде Google Play или App Store, но для сборщика проектов. Репозитории бывают локальными и удалёнными. Последние делятся на общедоступные и сторонние.
Локальный репозиторий расположен на вашем компьютере. Там Maven хранит библиотеки, которые вы используете в своих проектах.
Когда вы загружаете библиотеку в первый раз, Maven сохраняет её в локальном репозитории. Все последующие проекты используют уже загруженную версию, что позволяет сэкономить время на её скачивании.
Общедоступный, или центральный, репозиторий — это хранилище библиотек, предоставляемых Apache Maven. Именно к нему обращается сборщик по умолчанию.
Сторонние репозитории предоставляют какие-либо организации или сообщества. Чтобы Maven искал библиотеки именно в них, необходимо это настроить.
Библиотеки могут быть в состоянии снапшота (SNAPSHOT) или релиза (release). Снапшоты — это версии библиотек в разработке. Они могут меняться внутри без изменения номера версии. Это может привести к проблемам, так как версия библиотеки остаётся прежней, но её функциональность может измениться. Релизы — стабильные версии библиотек, которые не изменяются, а выпускаются под конкретным номером. Лучше всего использовать именно их.
Настройки работы Maven с репозиториями прописаны в settings.xml. Сам файл находится в папке conf вашей директории с Maven:
Откройте settings.xml в любом текстовом редакторе. Там много кода, но нам нужна секция . По умолчанию она выглядит так:
mirrors>mirrorId repositoryId Human Readable Name for this Mirror. http://my.repository.com/repo/path --> mirror> id>maven-default-http-blocker id> mirrorOf>external:http:* mirrorOf> name>Pseudo repository to mirror external repositories initially using HTTP. name> url>http://0.0.0.0/ url> blocked>true blocked> mirror> mirrors>
id — уникальный идентификатор для данного зеркала . В этом случае ID установлен как maven-default-http-blocker. Такая конфигурация блокирует внешние репозитории, использующие протокол HTTP. Это полезно, когда мы хотим пользоваться только локальными репозиториями.
mirrorOf — этот элемент указывает, для каких репозиториев будет применяться зеркало. У нас прописан шаблон external:http:*, который означает, что сборщик будет блокировать все внешние репозитории, использующие протокол HTTP, без каких-либо ограничений.
name — имя и описание для зеркала.
url — URL зеркала. Здесь указан фиктивный URL http://0.0.0.0/ в качестве заглушки.
blocked — определяет, блокируется указанное зеркало или нет. У нас установлено значение true, то есть доступ к внешним репозиториям заблокирован.
Если мы хотим, чтобы Maven искал библиотеки в других репозиториях, то должны добавить в блок по шаблону:
mirror> id>external-repos id> url>https://repo.example.com/maven2 url> mirrorOf>external:* mirrorOf> mirror>
В url впишите адрес желаемого репозитория. Теперь Maven сможет его найти.
Что запомнить
Резюмируем всё, что мы узнали про сборщик проектов:
- Maven облегчает рутинные задачи по сборке проектов на Java и некоторых других языках программирования.
- Главная сила Maven — это pom-файлы, позволяющие точно настроить сборку проекта с учётом всех используемых библиотек и фреймворков.
- Для хранения библиотек используются репозитории. Они могут быть локальными, то есть располагаться на вашем компьютере, и удалёнными. Это позволяет гибко настроить доступ к библиотекам и использовать нужные нам версии.
Больше интересного про код — в нашем телеграм-канале. Подписывайтесь!
Читайте также:
- Абстрактные классы в Java и их отличия от интерфейсов
- Тест. Какой язык создадите вы — Java или Python?
- HashMap в Java: что это такое и зачем нужно
«Зеркало» здесь — дублёр основного ресурса, позволяющий снизить на него нагрузку.
В macOS у пользователя User домашняя директория находится по адресу: /Users/User