Перейти к содержимому

Как добавить pom xml в idea

  • автор:

Maven

IntelliJ IDEA supports a fully-functional integration with Maven that helps you automate your building process. You can easily create a new Maven project, open and sync an existing one, add a Maven support to any existing IntelliJ IDEA project, configure and manage a multi-module project.

You can also create a Maven project and store it in the WSL environment or open it from the WSL file system. For more information, refer to the WSL section.

If you want to use a custom Maven version that is not bundled with IntelliJ IDEA, you need to install it locally.

Create a new Maven project

New project Maven

  1. If no project is currently open in IntelliJ IDEA, click New Project on the Welcome screen. Otherwise, select File | New | Project from the main menu.
  2. Name the new project and change its location if necessary.
  3. Select the Create Git repository to place the new project under version control. You will be able to do it later at any time.
  4. Select a language that you want to use in your project. Click if you want to add other languages available via plugins.
  5. Select Maven in the list of Build system .
  6. Specify project’s SDK (JDK) or use the default one.
  7. The selected Add sample code option will create a file with a basic code sample.
  8. In Advanced Settings , specify the following Maven coordinates that are added to the pom.xml file:
    • GroupId — a package of a new project.
    • ArtifactId — a name of your project.

For more information about Maven coordinates, refer to Maven naming conventions.

Create a new project with Maven archetype

Maven archetype

  1. Launch the New Project wizard. If no project is currently opened in IntelliJ IDEA, click New Project on the welcome screen. Otherwise, select File | New | Project from the main menu.
  2. Select Maven Archetype from the options on the left.
  3. Using options on the right, configure your project:
    • Name : specify the name of your project.
    • Location : specify the location of your project.
    • Create Git repository : Select the Create Git repository to place the new project under version control. You will be able to do it later at any time.
    • JDK : specify project’s SDK (JDK) or use the default one.
    • Catalog : specify which Maven repository you want to use in your project. The internal Maven catalog is a default one. You can also select the local repository that is located in the .m2 directory, or you can select Maven central repository. You can also click Manage Catalogs and add a custom repository if you need.
    • Archetype : select the needed Maven archetype. Click Add to specify the custom archetype.
    • Version : the version is specified automatically.
    • Additional properties : add additional properties

If you are creating a project using a Maven archetype, IntelliJ IDEA displays the Maven settings that you can use to set the Maven home path and Maven repositories. Also, you can check the archetype properties.

To modify or add archetype catalogs later in your project, refer to the Archetype Catalogs settings.

Create a Java EE project with Maven as a build tool

  1. Launch the New Project wizard. If no project is currently opened in IntelliJ IDEA, click New Project on the welcome screen. Otherwise, select File | New | Project from the main menu.
  2. Select Jakarta EE from the list of generators.
  3. Leave the default option Maven as your build tool system.
  4. Select additional libraries and frameworks.
  5. Specify your project’s name, location, and artifact coordinates. Click Create . IntelliJ IDEA creates a Maven project with the dedicated Maven tool window and adds necessary dependencies. For the more detailed information, refer to Tutorial: Your first Java EE application.

Open an existing Maven project

  1. Go to File | Open . Alternatively, click Open on the welcome screen. If you have some custom plugins that require you to import your project from the IntelliJ IDEA model, press Control+Shift+A and search for the Project from Existing Sources action.
  2. In the dialog that opens, select the pom.xml file of the project you want to open. Click OK .
  3. In the dialog that opens, click Open as Project .

IntelliJ IDEA opens and syncs the Maven project in the IDE. If you need to adjust importing options when you open the project, refer to the Maven settings. For example, if you have Maven options configured in the maven/config file and want to use them in your project, select the Use settings from .mvn/maven.config option in the Maven setting.

If you have a Maven project with the configured Maven wrapper then IntelliJ IDEA will take the Maven version from the maven.properties file and add it as the Maven home path.

Configure the Maven settings before opening a new project

You can configure IntelliJ IDEA to display Maven settings before you open a new Maven project. (A new Maven project in this case is the existing project that you open in IntelliJ IDEA for the first time.) Since these are application-level settings, they are applied to any new project you open.

Maven Settings

  1. On the Welcome screen, select Customize | All Settings . Alternatively, go to File |New Project Setup | Preferences for New Projects .
  2. In the Settings dialog, select Build, Execution, Deployment | Build Tools | Maven .
  3. In the Maven settings dialog, select the Show settings dialog for new Maven projects .
  4. Click OK to save the changes. Next time you open a new project, IntelliJ IDEA displays the Maven Settings dialog where you can specify a location of the local Maven repository and a user settings file.

Add a new Maven module to an existing project

You can add a Maven module to the project in which you are already working.

  1. In the Project tool window, right-click the project folder and select New | Module . Alternatively, go to File| New | Module to open the New Module wizard.
  2. If you used the main menu to add a module, then the process of adding a module is the same as Creating a new Maven project. If you are adding submodules by right-clicking the root folder then the process of adding a new module is shorter. You need to specify the name of your module in the Name field. The rest of the information is added automatically, and you can use either the default settings or change them according to your preferences.

Configure a multi-module Maven project

You can create a multi-module Maven project in IntelliJ IDEA. The multi-module project is defined by a parent POM file with several submodules.

If you have the Maven version 3.7 or later installed, IntelliJ IDEA will support importing a project from the MNG-6656 model.

In this case when you open a child POM file in the editor, you don’t have to specify a version inside the parent tags if it is located in the relativePath by default. If you add a dependency to a module in the same project, you don’t have to specify a version of the dependent module.

  1. Create a Maven parent project. IntelliJ IDEA creates a standard Maven layout including an src folder.
  2. In the Project tool window, remove the src folder since you would only need it in the very rare cases. For your general project, you don’t need the src folder for the parent POM.
  3. In the Project tool window, right-click your project (or from the main menu, click File ) and select New | Module to add a subproject.
  4. In the New Module wizard following the instructions on how to add a module, specify the necessary information and click Finish . The src folder is created automatically, and you can open POM and add a packaging that you need. IntelliJ IDEA adds the module to the parent project. IntelliJ IDEA also adds name and the description of the subproject to the parent POM. the parent POMIn a multi-module project, the parent POM needs to have a pom packaging. Last, but not least, IntelliJ IDEA adds the description of the parent POM to the subproject’s POM. the subproject POMYou can click in the left gutter to quickly open the parent POM from your subproject.
  5. You can also add dependencies to the parent POM that will be inherited by the subprojects. Parent POM: added dependency
  6. Open Maven tool window to see that all changes made in the parent POM are reflected in subprojects. the Maven tool window

Access the Maven settings

Use the Maven settings to configure options such as Maven version, local repository, offline mode, and so on.

  1. In the Settings dialog ( Control+Alt+S ), go to Build, Execution, Deployment| Maven . Click on the toolbar, in the Maven tool window to access the Maven settings.
  2. On the Maven settings page, configure the available options and click OK to save the changes.

Use the Maven wrapper or a custom version of Maven

The Maven2 version is not bundled with IntelliJ IDEA. If you need to use it in your project, download and enable the Maven2 support plugin.

For a custom version, Download the needed Maven version on your computer.

the Maven settings: Maven home path

  1. From the main menu select File | Settings | Build, Execution, Deployment | Build Tools | Maven .
  2. On the Maven settings page, in the Maven home path field, specify the location of the Maven custom version installation. For the Maven wrapper, select the use Maven wrapper option from the list. In this case the version of Maven defined in the .mvn/wrapper/maven-wrapper.properties file will be used.
  3. Click OK .

Change the JDK version in a Maven project

There are several places where you can change the JDK version that will affect not only your current project, but the whole application as well.

Change the JDK version in the Project Structure

Changing the JDK version in the Project Structure dialog will only affect the current project.

Project Structure dialog / Project page

  1. Go to File | Project Structure Control+Alt+Shift+S .
  2. In the dialog that opens, in Project SDK , specify the JDK version and click OK to save the changes.

Change the JDK version for the Maven runner

When IntelliJ IDEA runs Maven goals, it will use the JDK version specified for the Maven runner. By default, IntelliJ IDEA uses the project’s JDK.

Changing the JDK for the Maven runner will only affect the current project.

Maven Settings / Runner page

  1. In the Settings dialog ( Control+Alt+S ), go to Build, Execution, Deployment | Maven | Runner .
  2. On the page that opens, in the JRE field, select the JDK version.

Change the JDK version for the Maven importer

Changing the JDK version for the Maven importer will affect the whole application since it is a part of the Maven global settings. If you want to use the same JDK version as you use in your project for syncing or resolving dependencies, change the JDK version for the importer.

Maven Settings / Importing page

  1. In the Settings dialog ( Control+Alt+S ), go to Build, Execution, Deployment | Maven | Importing .
  2. On the page that opens, in the JDK for importer field, select the same JDK version as you used in the Project Structure and click OK to save the changes.

Сборка Java-проекта с использованием Maven

Этот урок освещает создание вами простого Java-приложения с использованием Maven.

Что вы создадите

Вы создадите простое приложение и соберете его с помощью Maven.

Что вам потребуется

  • Примерно 15 минут свободного времени
  • Любимый текстовый редактор или IDE
  • JDK 6 и выше

Как проходить этот урок

Как и большинство уроков по Spring, вы можете начать с нуля и выполнять каждый шаг, либо пропустить базовые шаги, которые вам уже знакомы. В любом случае, вы в конечном итоге получите рабочий код.

Чтобы начать с нуля, перейдите в Настройка проекта.

  • Загрузите и распакуйте архив с кодом этого урока, либо кнонируйте из репозитория с помощью Git: git clone https://github.com/spring-guides/gs-maven.git
  • Перейдите в каталог gs-maven/initial
  • Забегая вперед, установите Maven

Когда вы закончите, можете сравнить получившийся результат с образцом в gs-maven/complete .

Настройка проекта

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

Создание структуры каталогов

В выбранном вами каталоге проекта создайте следующую структуру каталогов; к примеру, командой mkdir -p src/main/java/hello для *nix систем:

+-- src +-- main +-- java +-- hello

Внутри src/main/java/hello директории вы можете создать любые Java-классы, какие вы хотите. Для простоты и согласованности с остальной частью урока, Spring рекомендует вам создать два класса: HelloWorld.java и Greeter.java .

package hello; public class HelloWorld < public static void main(String[] args) < Greeter greeter = new Greeter(); System.out.println(greeter.sayHello()); >>
package hello; public class Greeter < public String sayHello() < return "Hello world!"; >>

Теперь, когда у вас есть проект, который вы можете собрать с Maven, вам нужно установит сам Maven.

Maven можно получить, скачав zip-файл с maven.apache.org/download.cgi. Необходимы только бинарные файлы, так что ищите ссылку на архив с именем apache-maven-version-bin.zip или apache-maven-version-bin.tar.gz.

Распакуйте архив и добавьте путь к каталогу bin в переменную окружения path.

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

mvn -v

Если всё было сделано правильно, то вы увидите сообщение примерно такого содержания:

Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 07:51:28-0600) Maven home: /usr/share/maven Java version: 1.7.0_09, vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x", version: "10.8.3", arch: "x86_64", family: "mac"

Теперь у вас есть установленный Maven.

Создание простой сборки Maven

Теперь, когда Maven установлен, вам необходимо создать определение Maven-проекта. Maven-проекты определяются как XML-файлы с названием pom.xml. Помимо всего прочего, этот файл определяет имя проекта, версию, а также зависимости от сторонних библиотек.

Создайте файл с названием pom.xml в корневом каталоге проекта и наполните его следующим содержанием:


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
org.springframework
gs-maven
jar
0.1.0




org.apache.maven.plugins
maven-shade-plugin
2.1


package

shade



implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
hello.HelloWorld








За исключением дополнительного элемента , это простейший из pom.xml файлов, необходимый для сборки Java проекта. Он включает следующие детали конфигурации проекта:

  • — версия POM-модели (всегда 4.0.0)
  • — группа или организация, к которой принадлежит проект. Чаще всего выражается в виде перевернутого наоборот доменного имени
  • — имя, которое будет передано библиотеке экземпляра(artifact) проекта (к примеру, имя его JAR или WAR файла)
  • — версия, с которой будет собран проект
  • — как проект должен быть упакован. По умолчанию, с «jar» упаковывается в JAR-файл, «war» — WAR-файл

Когда речь заходит о выборе схемы управления версиями, Spring рекомендует [семантическое управление версиями] semver.org подход.

На данном этапе мы имеем минимальное, но уже рабочее определение Maven-проекта.

Сборка Java кода

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

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

mvn compile

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

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

mvn 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 :

mvn install

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

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

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

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

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

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

package hello; import org.joda.time.LocalTime; public class HelloWorld < public static void main(String[] args) < LocalTime currentTime = new LocalTime(); System.out.println("The current local time is: " + currentTime); Greeter greeter = new Greeter(); System.out.println(greeter.sayHello()); >>

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

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

 

joda-time
joda-time
2.2

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

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

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

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

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

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


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
org.springframework
gs-maven
jar
0.1.0




joda-time
joda-time
2.2







org.apache.maven.plugins
maven-shade-plugin
2.1


package

shade



implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
hello.HelloWorld








Полная версия pom.xml использует Maven Shade Plugin как удобный инструмент для создание выполняемого JAR-файла. Целью данного урока является показать, как начать работать с Maven, не используя, в частности, этот плагин.

Итог

Поздравляем! Вы создали простой, но эффективный файл сборки Maven для сборки Java проектов.

С оригинальным текстом урока вы можете ознакомиться на spring.io.

Добавить maven в IntelliJ IDEA в обычный java проект

Как мне это (именно версии 7.0.13). http://search.maven.org/#artifactdetails%7Cit.unimi.dsi%7Cfastutil%7C7.0.13%7Cjar добавить в IntelliJ IDEA в обычный java проект ? Не вручную, cкачивая jar.

Отслеживать
33.1k 2 2 золотых знака 33 33 серебряных знака 64 64 бронзовых знака
задан 3 сен 2016 в 11:43
713 1 1 золотой знак 6 6 серебряных знаков 25 25 бронзовых знаков

4 ответа 4

Сортировка: Сброс на вариант по умолчанию

введите сюда описание изображения

  1. Нажать на папку с проектом правой кнопкой
  2. Выбрать «Добавить поддержку фреймворка»
  3. Выбрать из списка Maven

Отслеживать
ответ дан 10 июл 2019 в 6:08
Lukyanov Mikhail Lukyanov Mikhail
251 2 2 серебряных знака 4 4 бронзовых знака

Поздний ответ, наверное, но для истории:

Можно в корень обычного проекта в IDEA добавить pom.xml (хоть из другого проекта), подправить ему group, artifact, зависимости. Потом в контекстном меню для этого файла выбрать «Add as Maven Project». Проект станет теперь maven, дальше уже настраиваем его как обычный maven-проект.

Update простейший XML файл имеет вид

  4.0.0 . . 1.0-SNAPSHOT  

Отслеживать
33.1k 2 2 золотых знака 33 33 серебряных знака 64 64 бронзовых знака
ответ дан 21 июл 2017 в 15:32
Полина Бевад Полина Бевад
141 1 1 серебряный знак 2 2 бронзовых знака
Если вы еще добавите шаблон pom.xml , ответу цены не будет.
21 июл 2017 в 15:38

Можно выгрузить библиотеку из Maven.
Для этого:
1. Войти в структуру проекта;

2. В разделе «Библиотеки» выбрать «Из Maven»;

3. Ввести путь к библиотеке (можно искать как по groupId, так и по artifactId).
введите сюда описание изображения

Maven. Repositories

The table shows the list of Maven repositories, encountered in the current project (including repositories in settings.xml ), with their URLs, type (local or remote) and the date of the most recent update.

If you need to add a Maven repository, use pom.xml . For more information, refer to the Maven documentation.

Indexed Maven Repositories

This area contains Maven repositories that are configured in the Effective POM file which lists the default configurations, profiles and goals. IntelliJ IDEA updates the list of repositories automatically.

If you open a project that contains additional repositories specified, then the repositories are added to the Indexed Maven Repositories list and you can update the indexes.

If you have a problem with your repository, make sure that the indexing service is enabled on the Nexus repository or other repositories you use in your environment.

Click this button to update indexes of the selected repository. It might be helpful in case you expect to get information for newly deployed artifacts such as new versions of libraries that you use in the project. Also, when you use Maven dependencies completion in pom.xml or generation of Maven dependencies using Maven Artifact Search dialog.

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

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