Как добавить зависимость в maven intellij idea
Перейти к содержимому

Как добавить зависимость в maven intellij idea

  • автор:

Maven dependencies

IntelliJ IDEA lets you manage Maven dependencies in your project. You can add, import Maven dependencies, view them in the diagram, and also analyze them.

Add a Maven dependency

IntelliJ IDEA lets you add a Maven dependency to your project. We recommend that you specify the dependency inside your POM . Dependencies that you set up manually inside IntelliJ IDEA module settings will be discarded on the next Maven project reload.

Open your POM in the editor.

Press Alt+Insert to open the Generate context menu.

From the context menu, select Dependency .

In the Maven Artifact Search tool window, in the search field, start typing the name of your dependency. In the list of results select the one you need and click Add .

Maven Artifact Search

IntelliJ IDEA adds the dependency to your pom.xml .

the Maven Tool Window

IntelliJ IDEA also adds the dependency to the Dependencies node in the Maven tool window and to the External Libraries in the Project tool window.

If the added dependency has its own transitive dependencies, IntelliJ IDEA displays them in both tool windows.

Enable annotation processors

Open your POM file.

Specify the annotationProcessors and annotationProcessorPaths options.

For example, check the following code:

For more information, refer to Maven.

Re-import your project. IntelliJ IDEA creates an annotation processors profile, enables the annotation processing and adds the appropriate path to the Annotation Processor settings located in Settings | Build, Execution, Deployment | Compiler .

Centralize dependency information

In a multi-module Maven project, the dependency in the parent POM will be inherited by all sub projects. You can use dependencyManagement to consolidate and centralize the management of the dependencies’ versions.

Open your POM in the editor.

Press Alt+Insert to open the Generate context menu.

From the context menu, select the Managed Dependency option that will show you the list of the dependencies that are defined in the dependencyManagement section of your parent POM in a multi-module project. IntelliJ IDEA also shows the list of dependencies from the BOM files.

Select the desired dependency and click OK . The dependency is added to the POM. You don’t need to specify the version on the dependency it will be taken from the DependencyManagement .

However, if you want to overwrite the defined version, you need to include version when you add the managed dependency to the POM.

Add a scope for the Maven dependency

You can add a scope for your dependency using POM. In this case IntelliJ IDEA will execute the dependency at the specified phase.

In your POM, in the dependency description add scope and using the code completion add the name of the scope.

Import your changes. The name of the scope is displayed in the Maven tool window. In the Project Structure dialog, on the Modules page you can see that the scope of the dependency is also displayed.

the Project Structure dialog

Note that changing dependency’s scope in the Project Structure dialog will not affect the pom.xml file.

You can also add a custom jar file as a dependency using the Maven scope system when you define your dependency. However, note that this dependency will only be available on your machine and you can use it only for the local deployment.

Work with Maven transitive dependencies

You can view transitive dependencies that were pulled in with the added or imported Maven dependency. You can check their versions, change them, or exclude those dependencies altogether.

The Maven tool window displays the direct dependency and all its transitive dependencies that were pulled in.

View the transitive dependency

In your project’s POM, press Ctrl and hover the mouse over the dependency.

Click the dependency to open the dependency’s POM.

In the dependency POM, view the active dependency, its transitive dependencies and their versions.

the dependency POM with transitive dependencies

You can check the origin from which the dependency was pulled in.

Exclude the transitive dependency

You can exclude a transitive dependency if you want.

Open the dependency POM and find the transitive dependency you want to exclude. Copy groupId and artifactId .

In your project POM, underneath your active dependency, enter exclusions and using code completion paste the copied info of the dependency you want to exclude.

You can use the Exclude command from the context menu in the Maven dependency diagram to quickly exclude the specified dependency from POM and the respective tool windows.

POM with dependency exclusion

The dependency is also excluded from the Project and Maven tool windows.

Import Maven dependencies

You can import dependencies to your Maven project. When IntelliJ IDEA imports the added dependency, it parses the dependency and updates your project.

In the pom.xml file, add a dependency you need. When you change the pom.xml , IntelliJ IDEA displays a notification suggesting to load the changes. Click in the editor to import the dependency and update your project.

In the Maven tool window, press . In this case you manually trigger the re-importing process of all projects and their dependencies.

View Maven dependencies as a diagram

Make sure that the Diagrams and Maven Extension bundled plugins are enabled.

IntelliJ IDEA lets you view and work with Maven dependencies in a diagram format.

Generate a diagram

In the Maven tool window, on the toolbar, click or select the appropriate option from the context menu.

In the POM, right-click anywhere in the editor to open the context menu and select Maven | Show Dependencies . Alternatively, press Control+Alt+Shift+U or Control+Alt+U .

In the diagram window, IntelliJ IDEA displays the sub project and all its dependencies including the transitive ones.

View the diagram structure

Generate a diagram.

Click Structure in the left toolbar. IntelliJ IDEA opens the Structure tool window that displays a map of your diagram with a small preview of the selected block and its neighbors.

the Structure view

Use the context menu to zoom in and out, move canvas, change layout, and export part of the diagram into an image.

You can perform different actions while in the diagram window.

Change the visibility level

You can change the visibility level and, for example, view dependencies that have a specific scope (compile, test, and so on).

In the diagram window, select the sub project and click .

From the list, select the dependency scope you want to see. IntelliJ IDEA displays only the specified dependency scope.

Navigate to POM

You can easily navigate to POM from the diagram window.

Select the desired node, and press F4 , or choose Jump to Source on its context menu. The corresponding file opens in the editor.

You can check conflicts and duplicates by clicking icon in the diagram window.

Check conflicts and duplicates

In the diagram window, click icon.

The red arrow points to dependencies that contain duplicates or errors. IntelliJ IDEA also displays dependencies’ versions to help you resolve the conflicts. Double-click the dependency to open its POM.

Show path from the selection to the root

You can select dependencies and see how they are included into the project.

In the diagram window, select a dependency for which you want to see a connection to a project. If you want to select several dependencies at once, hold down Shift and make the selection.

Show neighbors of the selected node

You can select dependencies and see what other dependencies are connected to the selected nodes. It might be helpful if you have a large diagram and want to focus on just a part of it.

In the diagram window, select a dependency you need. If you want to select several dependencies at once, hold down Shift and make the selection.

Exclude a dependency

You can use a diagram to exclude a dependency from the project’s POM.

Select a dependency in the diagram window.

From the context menu, choose Exclude .

From the list, select the module (if any) where the exclusion definition will be added. The selected dependencies will be removed from diagram, and the exclusion section will be added to the corresponding dependency in the module’s POM.

Exclude a dependency

You can undo this operation by pressing Control+Z before you import the changes.

Dependency analyzer

Maven dependency analyzer lets you quickly see and analyze resolved dependencies, the unresolved ones, dependencies with conflicts, and transitive dependencies in your project and subprojects.

Analyze dependencies

On the toolbar in the Maven tool window, click .

Alternatively, in the Maven tool window, right-click the needed dependency and select Analyze Dependencies from the context menu. You can also right-click a module in the Project view and use the same action.

In the Dependency Analyzer window, you can narrow down your analysis scope, check only the conflicted dependencies, or check usages.

If you want to see the needed dependency in the pom.xml file, right-click the dependency and select Go to Maven Dependency . If you click Open Maven Config on the specific dependency, IntelliJ IDEA will open the dependency’s POM file.

You can also click Go to Package Search to navigate to the dependency in quiestion in the Work with the Dependencies tool window.

If the duplicate dependency is found, it will be greyed out.

duplicate dependencies

For more information on available options and icons in the Dependency Analyzer window, refer to the reference section.

Dependency analyzer tool window reference

You can see scopes in which every dependency is used in the project. To narrow down the list of the dependencies based on their scope, select the appropriate option from the list of scopes.

Show Conflicts Only

Click to see only unresolved or conflicted dependencies.

Click and select Show GroupId to display GroupId in the list of dependencies.

Toggle to display the list of dependencies in a form of nodes or in the flat list.

Управление зависимостями в IntelliJ IDEA

В этом руководстве, в продолжение темы просмотра зависимостей, мы рассмотрим управление зависимостями в IntelliJ IDEA.

Мы рассмотрим различные способы добавления зависимостей в ваш проект, а также способы добавления, обновления и удаления зависимостей с помощью Package Search.

Добавление зависимостей

Существует несколько способов добавления новых зависимостей в ваш проект.

Из файла сборки с помощью копирования/вставки

Вы наверняка копировали зависимость из репозитория Maven (или другого веб-сайта) и вставляли ее в свой файл сборки.

Например, мы можем скопировать формат Gradle для этой зависимости и вставить его в наш файл build.gradle.

Или, если мы используем Maven, мы можем скопировать формат Maven xml в наш pom.xml.

Знаете ли вы, что если вы скопируете и вставите зависимость Maven XML в файл build.gradle, IntelliJ IDEA автоматически преобразует ее в правильный формат для Gradle?

Из файла сборки с помощью автозавершения кода

Мы также можем добавить зависимости в наш файл сборки, используя автозавершение кода. Например, давайте добавим новую зависимость в наш файл pom.xml.

Мы видим, что IntelliJ IDEA автоматически дополняет xml зависимости, и мы можем искать нужную зависимость, в данном примере AssertJ.

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

Автозавершение кода работает и в Gradle, как вы можете видеть ниже.

Из файла сборки с помощью генерации кода

Мы также можем использовать генерацию кода из файла сборки для добавления зависимостей.

В файле сборки pom.xml в проекте Maven вызовите Package Search (поиск пакетов) с помощью ⌘N (в macOS) или Alt+Insert (в Windows и Linux) и в открывшемся меню выберите Add dependency.

Откроется окно инструмента Dependencies (Зависимости).

Обратите внимание: если мы используем Gradle, мы можем сделать то же самое в нашем файле build.gradle.

Из окна инструмента Dependencies

В качестве альтернативы мы можем напрямую открыть окно инструмента Dependencies.

Ярлыка для открытия окна инструмента Dependencies не существует, поэтому мы можем использовать Recent Files, ⌘E (на Mac) или Ctrl+E (в Windows/Linux) и ввести «dependencies», чтобы открыть окно инструмента Dependencies.

В качестве альтернативы мы можем открыть его, нажав Quick Launch в левом нижнем углу и выбрав Dependencies.

В окне инструмента Dependencies мы можем искать зависимость. Например, давайте поищем AssertJ.

Обратите внимание, что мы можем выбрать область видимости для этой зависимости.

Названия областей видимости зависят от инструмента сборки, с которым вы работаете.

Поскольку это тестовая зависимость, и мы используем Gradle в этом проекте, мы можем установить область видимости на testImplementation.

Мы также можем выбрать версию, которую хотим использовать.

Мы можем сделать то же самое в Maven.

Обратите внимание, что названия областей видимости для Maven отличаются от Gradle.

В Maven мы можем установить область видимости для тестовой зависимости как test.

Когда мы нажимаем Add, мы видим, что зависимость добавлена в файл сборки.

Если номер версии показан красным цветом, это означает, что IntelliJ IDEA еще не загружала эту библиотеку.

Щелкните Load Maven Changes, чтобы IntelliJ IDEA обновила свои зависимости на основе изменений в файле pom.xml или build.gradle.

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

Далее ищем jackson-databind. Мы видим, что доступно несколько версий.

Поскольку мы выбрали Only stable, в списке отображаются только стабильные версии.

Если мы снимем флажок с этой опции, мы увидим, что в список версий также входят кандидаты на выпуск.

Для производственного кода мы, вероятно, хотим использовать стабильные версии, поэтому давайте снова установим флажок Only stable.

Если эта опция включена, IntelliJ IDEA исключит все зависимости, не имеющие стабильных версий, и скроет их в списке.

Теперь мы можем выбрать последнюю стабильную версию и добавить ее в наш проект. Давайте также снова загрузим Maven Changes.

Наконец, давайте также добавим новую зависимость для модуля Kotlin.

Давайте переключимся на модуль Kotlin и откроем pom.xml для этого модуля.

Откройте окно Dependencies Tool и найдите Ktor.

Обратите внимание, что некоторые зависимости помечены как Multiplatform (многоплатформенные).

Если мы хотим видеть только многоплатформенные зависимости Kotlin, мы можем установить флажок Kotlin multiplatform, как показано ниже.

Когда мы нажимаем Add справа от зависимости Ktor, мы видим, что Ktor добавлен в список зависимостей и в pom.xml для модуля Kotlin.

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

Нам также необходимо будет поддерживать наши зависимости в актуальном состоянии.

Чтобы показать вам, как IntelliJ IDEA может в этом помочь, мы используем в качестве примера этот крайне устаревший проект.

В pom.xml ниже мы видим, что несколько зависимостей отмечены волнистыми линиями под ними.

IntelliJ IDEA покажет предложение по обновлению, когда мы наведем указатель мыши на зависимость, и мы можем щелкнуть по предложению для обновления зависимостей.

В качестве альтернативы мы можем использовать Context Actions (контекстные действия) ⌥⏎ (в macOS) или Alt+Enter (в Windows и Linux) для обновления этих зависимостей.

Мы также можем обновить наши зависимости, используя окно Dependencies tool.

Окно Dependencies tool подскажет нам, есть ли более новая версия зависимости, как мы видим здесь.

Мы можем выбрать версию для обновления, нажав на номер версии в списке.

Обратите внимание, что нам необязательно использовать последнюю версию.

Мы также можем автоматически обновить зависимость до последней версии, нажав Upgrade для этой конкретной зависимости.

Или мы можем даже обновить все наши зависимости сразу, нажав на ссылку Upgrade all.

Удаление зависимостей

Наконец, мы можем удалить зависимости, которые нам больше не нужны. В окне Dependencies tool давайте удалим jackson-databind из модуля Java.

Выберем зависимость, которую хотим удалить (jackson-databind), и на панели сведений о зависимости справа нажимаем кнопку More (три точки) и выбираем Remove.

Мы увидим, что зависимость удалена из pom.xml и списка зависимостей. Чтобы удалить зависимость из всего проекта, выберите All Modules слева.

Резюме и ярлыки

Теперь мы знаем различные способы просмотра зависимостей нашего проекта в IntelliJ IDEA, а также различные фокусы для каждого представления.

Часть 4. Основы Maven

Java-университет

Для начала нужно установить Maven, скачав его по этой ссылке.

Далее необходимо распаковать скачанный архив и установить переменной окружения M2_HOME ссылку на местонахождение распакованного архива. Например, C:\Program Files\maven\

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

Если отобразится информация о версии Maven, Java и т.д., все готово к работе.

Теперь открой IntelliJIDEA и создай новый проект. В первом же окне выбери Maven:

Нажми Next и заполни следующее диалоговое окно:

Далее стандартно создай проект в необходимом месте.

После того, как проект создался, обрати внимание на его структуру:

  • в папке src/main/java содержатся java-классы;
  • в src/main/resources — ресурсы, которые использует наше приложение (HTML-страницы, картинки, таблицы стилей и тд);
  • src/test — для тестов.

Управление зависимостями в Maven

На сайте библиотеки. Если нам нужен Apache Commons IO, переходим на официальный сайт, выбираем вкладку Dependency Information. Здесь есть вся необходимая информация — ее можно просто скопировать и добавить в наш раздел dependencies.

В Maven-репозитории. В поиске введи “apache commons io”, и ты увидишь все доступные версии библиотеки. После выбора нужной, просто скопируй:

и добавь в свой pom.xml.

Виды Maven-репозиториев

Сборка Java-проекта с помощью Maven

  1. clean — удаляются все скомпилированные файлы из каталога target (место, в котором сохраняются готовые артефакты);
  2. validate — идет проверка, вся ли информация доступна для сборки проекта;
  3. compile — компилируются файлы с исходным кодом;
  4. test — запускаются тесты;
  5. package — упаковываются скомпилированные файлы (в jar, war и т.д. архив);
  6. verify — выполняются проверки для подтверждения готовности упакованного файла;
  7. install — пакет помещается в локальный репозиторий. Теперь он может использоваться другими проектами как внешняя библиотека;
  8. site — создается документация проекта;
  9. deploy — собранный архив копируется в удаленный репозиторий.

через командную строку:

используя Intellij IDEA:

Часть 4. Основы Maven - 7

До запуска package выполняются фазы validate, compile, test. Исключение — фаза clean. Ее желательно вызывать перед каждой новой сборкой проекта. Фазы можно перечислить через пробел:

Import Maven dependencies in IntelliJ IDEA

I just imported a project from subversion to IntelliJ IDEA 11 — it’s a maven project. But I have a problem in maven library dependencies so that I can’t include all maven dependencies automatically — IDEA shows dependency errors only when I open that class/ Thats what I get here:

enter image description here

So I want all dependencies to be added automatically — is that possible or do I have to go through all class files to identify and add maven dependencies?!

UPDATE: After doing some modifications I found how to resolve my problem in some way. Thats what I did: enter image description here

but I think logically it will not include and check new dependencies ahead. Is there any settings area for this in intelliJ — auto export dependencies to classpath?

Zaur Guliyev's user avatar

39 Answers 39

IntelliJ should download and add all your dependencies to the project’s classpath automatically as long as your POM is compliant and all the dependencies are available.

When importing Maven projects into IntelliJ an information box usually comes up asking you if you want to configure Auto-Import for Maven projects. That means that if you make any changes to your POM those changes will be loaded automatically.

You can enable such feature going to File > Settings > Maven > Importing, there is a checkbox that says «Import Maven projects automatically».

If that doesn’t help, then I would suggest to make a full clean-up and start again:

  • Close your project window (and IntelliJ) and remove all *.iml files and all .idea folders (there should be one per module)
  • Run mvn clean install from the command line
  • Re-import the project into IntelliJ and pay attention when it asks you to enable auto-import

IntelliJ 2016 Update:

The Import Maven Projects automatically setting has been moved to Build, Execution, Deployment > Build Tools > Maven > Importing in your IntelliJ preferences.

Alonso Dominguez's user avatar

Fix before IntelliJ 14

File [menu] -> Settings -> maven -> importing and uncheck «use maven3 to import project»

Fix IntelliJ 15+

Ran into this again, with IntelliJ 15 this time, which has no «use maven3 to import» option available anymore. The cause was that sometimes IntelliJ «doesn’t parse maven dependencies right» and if it can’t parse one of them right, it gives up on all of them, apparently. You can tell if this is the case by opening the maven projects tool window (View menu -> Tool Windows -> Maven Projects). Then expand one of your maven projects and its dependencies. If the dependencies are all underlined in red, «Houston, we have a problem». enter image description here

You can actually see the real failure by mousing over the project name itself.

enter image description here

In my instance it said «Problems: No versions available for XXX» or «Failed to read descriptor for artifact org.xy.z» ref: https://youtrack.jetbrains.com/issue/IDEA-128846 and https://youtrack.jetbrains.com/issue/IDEA-152555

It seems in this case I was dealing with a jar that didn’t have an associated pom file (in our maven nexus repo, and also my local repository). If this is also your problem, «urrent work around: if you do not actually need to use classes from that jar in your own code (for instance a transitive maven dependency only), you can actually get away with commenting it out from the pom (temporarily), maven project reload, and then uncomment it. Somehow after that point IntelliJ «remembers» its old working dependencies. Adding a maven transitive exclude temporarily might also do it, if you’re running into it from transitive chain of dependencies.»

Another thing that might help is to use a «newer version» of maven than the bundled 3.0.5. In order to set it up to use this as the default, close all your intellij windows, then open preferences -> build, execution and deployment -> build tools -> maven, and change the maven home directory, it should say «For default project» at the top when you adjust this, though you can adjust it for a particular project as well, as long as you «re import» after adjusting it.

Clear Caches

Deleting your intellij cache folders (windows: HOMEPATH/.XXX linux

/.IdeaIC15) and/or uninstalling and reinstalling IntelliJ itself. This can also be done by going to File [menu] -> Invalidate Caches / Restart. . Click invalidate and restart . This will reindex your whole project and solve many hard-to-trace issues with IntelliJ.

Maven dependencies

IntelliJ IDEA lets you manage Maven dependencies in your project. You can add, import Maven dependencies, view them in the diagram, and also analyze them.

Add a Maven dependency

IntelliJ IDEA lets you add a Maven dependency to your project. We recommend that you specify the dependency inside your POM . Dependencies that you set up manually inside IntelliJ IDEA module settings will be discarded on the next Maven project reload.

Open your POM in the editor.

Press Alt+Insert to open the Generate context menu.

From the context menu, select Dependency .

In the Maven Artifact Search tool window, in the search field, start typing the name of your dependency. In the list of results select the one you need and click Add .

Maven Artifact Search

IntelliJ IDEA adds the dependency to your pom.xml .

the Maven Tool Window

IntelliJ IDEA also adds the dependency to the Dependencies node in the Maven tool window and to the External Libraries in the Project tool window.

If the added dependency has its own transitive dependencies, IntelliJ IDEA displays them in both tool windows.

Enable annotation processors

Open your POM file.

Specify the annotationProcessors and annotationProcessorPaths options.

For example, check the following code:

For more information, refer to Maven.

Re-import your project. IntelliJ IDEA creates an annotation processors profile, enables the annotation processing and adds the appropriate path to the Annotation Processor settings located in Settings | Build, Execution, Deployment | Compiler .

Centralize dependency information

In a multi-module Maven project, the dependency in the parent POM will be inherited by all sub projects. You can use dependencyManagement to consolidate and centralize the management of the dependencies’ versions.

Open your POM in the editor.

Press Alt+Insert to open the Generate context menu.

From the context menu, select the Managed Dependency option that will show you the list of the dependencies that are defined in the dependencyManagement section of your parent POM in a multi-module project. IntelliJ IDEA also shows the list of dependencies from the BOM files.

Select the desired dependency and click OK . The dependency is added to the POM. You don’t need to specify the version on the dependency it will be taken from the DependencyManagement .

However, if you want to overwrite the defined version, you need to include version when you add the managed dependency to the POM.

Add a scope for the Maven dependency

You can add a scope for your dependency using POM. In this case IntelliJ IDEA will execute the dependency at the specified phase.

In your POM, in the dependency description add scope and using the code completion add the name of the scope.

Import your changes. The name of the scope is displayed in the Maven tool window. In the Project Structure dialog, on the Modules page you can see that the scope of the dependency is also displayed.

the Project Structure dialog

Note that changing dependency’s scope in the Project Structure dialog will not affect the pom.xml file.

You can also add a custom jar file as a dependency using the Maven scope system when you define your dependency. However, note that this dependency will only be available on your machine and you can use it only for the local deployment.

Work with Maven transitive dependencies

You can view transitive dependencies that were pulled in with the added or imported Maven dependency. You can check their versions, change them, or exclude those dependencies altogether.

The Maven tool window displays the direct dependency and all its transitive dependencies that were pulled in.

View the transitive dependency

In your project’s POM, press Ctrl and hover the mouse over the dependency.

Click the dependency to open the dependency’s POM.

In the dependency POM, view the active dependency, its transitive dependencies and their versions.

the dependency POM with transitive dependencies

You can check the origin from which the dependency was pulled in.

Exclude the transitive dependency

You can exclude a transitive dependency if you want.

Open the dependency POM and find the transitive dependency you want to exclude. Copy groupId and artifactId .

In your project POM, underneath your active dependency, enter exclusions and using code completion paste the copied info of the dependency you want to exclude.

You can use the Exclude command from the context menu in the Maven dependency diagram to quickly exclude the specified dependency from POM and the respective tool windows.

POM with dependency exclusion

The dependency is also excluded from the Project and Maven tool windows.

Import Maven dependencies

You can import dependencies to your Maven project. When IntelliJ IDEA imports the added dependency, it parses the dependency and updates your project.

In the pom.xml file, add a dependency you need. When you change the pom.xml , IntelliJ IDEA displays a notification suggesting to load the changes. Click in the editor to import the dependency and update your project.

In the Maven tool window, press . In this case you manually trigger the re-importing process of all projects and their dependencies.

View Maven dependencies as a diagram

Make sure that the Diagrams and Maven Extension bundled plugins are enabled.

IntelliJ IDEA lets you view and work with Maven dependencies in a diagram format.

Generate a diagram

In the Maven tool window, on the toolbar, click or select the appropriate option from the context menu.

In the POM, right-click anywhere in the editor to open the context menu and select Maven | Show Dependencies . Alternatively, press Control+Alt+Shift+U or Control+Alt+U .

In the diagram window, IntelliJ IDEA displays the sub project and all its dependencies including the transitive ones.

View the diagram structure

Generate a diagram.

Click Structure in the left toolbar. IntelliJ IDEA opens the Structure tool window that displays a map of your diagram with a small preview of the selected block and its neighbors.

the Structure view

Use the context menu to zoom in and out, move canvas, change layout, and export part of the diagram into an image.

You can perform different actions while in the diagram window.

Change the visibility level

You can change the visibility level and, for example, view dependencies that have a specific scope (compile, test, and so on).

In the diagram window, select the sub project and click .

From the list, select the dependency scope you want to see. IntelliJ IDEA displays only the specified dependency scope.

Navigate to POM

You can easily navigate to POM from the diagram window.

Select the desired node, and press F4 , or choose Jump to Source on its context menu. The corresponding file opens in the editor.

You can check conflicts and duplicates by clicking icon in the diagram window.

Check conflicts and duplicates

In the diagram window, click icon.

The red arrow points to dependencies that contain duplicates or errors. IntelliJ IDEA also displays dependencies’ versions to help you resolve the conflicts. Double-click the dependency to open its POM.

Show path from the selection to the root

You can select dependencies and see how they are included into the project.

In the diagram window, select a dependency for which you want to see a connection to a project. If you want to select several dependencies at once, hold down Shift and make the selection.

Show neighbors of the selected node

You can select dependencies and see what other dependencies are connected to the selected nodes. It might be helpful if you have a large diagram and want to focus on just a part of it.

In the diagram window, select a dependency you need. If you want to select several dependencies at once, hold down Shift and make the selection.

Exclude a dependency

You can use a diagram to exclude a dependency from the project’s POM.

Select a dependency in the diagram window.

From the context menu, choose Exclude .

From the list, select the module (if any) where the exclusion definition will be added. The selected dependencies will be removed from diagram, and the exclusion section will be added to the corresponding dependency in the module’s POM.

Exclude a dependency

You can undo this operation by pressing Control+Z before you import the changes.

Dependency analyzer

Maven dependency analyzer lets you quickly see and analyze resolved dependencies, the unresolved ones, dependencies with conflicts, and transitive dependencies in your project and subprojects.

Analyze dependencies

On the toolbar in the Maven tool window, click .

Alternatively, in the Maven tool window, right-click the needed dependency and select Analyze Dependencies from the context menu. You can also right-click a module in the Project view and use the same action.

In the Dependency Analyzer window, you can narrow down your analysis scope, check only the conflicted dependencies, or check usages.

If you want to see the needed dependency in the pom.xml file, right-click the dependency and select Go to Maven Dependency . If you click Open Maven Config on the specific dependency, IntelliJ IDEA will open the dependency’s POM file.

You can also click Go to Package Search to navigate to the dependency in quiestion in the Work with the Dependencies tool window.

If the duplicate dependency is found, it will be greyed out.

duplicate dependencies

For more information on available options and icons in the Dependency Analyzer window, refer to the reference section.

Dependency analyzer tool window reference

You can see scopes in which every dependency is used in the project. To narrow down the list of the dependencies based on their scope, select the appropriate option from the list of scopes.

Show Conflicts Only

Click to see only unresolved or conflicted dependencies.

Click and select Show GroupId to display GroupId in the list of dependencies.

Toggle to display the list of dependencies in a form of nodes or in the flat list.

Maven. Часть 2 – Dependency

В этом уроке я вам покажу основную силу Maven, а именно как создать проект, который можно разрабатывать целой командой и при этом не потребуется каждому члену команды подключать необходимые библиотеки к проекту, давайте начнем.
И так начнем с того, зачем вам нужен Maven? В статье Maven. Часть 1 – Знакомство и настройка мы уже немного разобрали что это и как настроить.

Тут я хочу вам показать как использовать данный инструмент, а покажу вам его использование на примере JUnit тестирования.

Шаг 1. Создание Maven проекта

Запускаем нашу всем любимую Intellij IDEA и нажимаем File->Create New Project

Шаг 2.

Теперь в корне проекта вы должны увидеть файл pom.xml.

И вот что вы должны видеть:

С помощью этого файла и осуществляется настройка сборки вашего проекта. К примеру вам нужно собрать проект в *.jar файл, для этого вам достаточно указать это в pom.xml. Как собрать проект в jar файл вы можете посмотреть тут.

Это файл изначально имеет default (поумолчанию) структуру.

Шаг 3. Используем Dependency

Что же такое dependency и для чего они нужны?

Dependency – это зависимости от библиотек, а если точней, то это и есть библиотека, которую вы бы хотели подключить к проекту.

Рассмотрим на базовом шаблоне:

В выше приведенном примере я продемонстрировал подключение библиотеки JUnit 4.11 к проекту, теперь при сборке проекта эта библиотека упакуется в мой *.jar или *.war архив, а также теперь мы в наших классах можем обращаться к объектам библиотеки JUnit.

<dependencies> – тут мы размещаем список dependency (библиотек), которые используются в проекте;

<dependency> – библиотека используемая проектом;

<groupId> – идентификатор группы библиотеки;

<artifactId> – артефакт (библиотека);

<version> – версия библиотеки;

<scope> – этап использования.

Шаг 4. Структура проекта

Стандартная структура каталогов:

Стандартная структура каталогов — одна из реализаций этого принципа.

Поскольку проект её придерживается, отпадает необходимость специфицировать пути к файлам, что сильно упрощает pom.xml.

Следующая структура показывает важнейшие каталоги.

Корневой каталог проекта:

– pom.xml и все дальнейшие подкаталоги;

– src: все исходные файлы;

src/main : исходные файлы собственно для продукта;

src/main/java : Java-исходный текст;

src/main/resources : другие файлы, которые используются при компиляции или исполнении, например Properties-файлы;

src/test : исходные файлы, необходимые для организации автоматического тестирования;

src/test/java : JUnit-тест-задания для автоматического тестирования;

target : все создаваемые в процессе работы Мавена файлы;

target/classes : компилированные Java-классы.

Шаг 5. Жизненный цикл

Жизненный цикл проекта — это список поименованных фаз, определяющий порядок действий при его построении.

Maven использует по умолчанию следующий жизненный цикл:

1) archetype – создание темплейта и обработка ресурсов. На этой фазе разрешаются и, при необходимости, скачиваются из интернета зависимости;

2) compile – компиляция;

3) обработка тестовых ресурсов (например — скачивается из интернета JUnit-пакет);

4) компиляция тестов (тестирующие классы не передаются конечным пользователям);

5) test – тестирование;

6) package – упаковка (обычно речь идёт о создании JAR– или WAR-файла);

7) install – инсталляция проекта в локальном Maven-репозитории (теперь он доступен как модуль для других локальных проектов);

8) deploy – инсталляция в удаленном Maven-репозитории (теперь стабильная версия проекта доступна широкому кругу разработчиков).

Maven имеет также стандартный жизненный цикл для чистки (cleaning) и для генерации его страницы (site). Если бы ‘clean’ было частью обычного жизненного цикла, проект подвергался бы чистке при каждом построении, что нежелательно.

Стандартные жизненные циклы могут быть существенно дополнены Maven-плагинами и Maven-архетипами.

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

Import Maven dependencies in IntelliJ IDEA

I just imported a project from subversion to IntelliJ IDEA 11 — it’s a maven project. But I have a problem in maven library dependencies so that I can’t include all maven dependencies automatically — IDEA shows dependency errors only when I open that class/ Thats what I get here:

enter image description here

So I want all dependencies to be added automatically — is that possible or do I have to go through all class files to identify and add maven dependencies?!

UPDATE: After doing some modifications I found how to resolve my problem in some way. Thats what I did: enter image description here

but I think logically it will not include and check new dependencies ahead. Is there any settings area for this in intelliJ — auto export dependencies to classpath?

Zaur Guliyev's user avatar

39 Answers 39

IntelliJ should download and add all your dependencies to the project’s classpath automatically as long as your POM is compliant and all the dependencies are available.

When importing Maven projects into IntelliJ an information box usually comes up asking you if you want to configure Auto-Import for Maven projects. That means that if you make any changes to your POM those changes will be loaded automatically.

You can enable such feature going to File > Settings > Maven > Importing, there is a checkbox that says «Import Maven projects automatically».

If that doesn’t help, then I would suggest to make a full clean-up and start again:

  • Close your project window (and IntelliJ) and remove all *.iml files and all .idea folders (there should be one per module)
  • Run mvn clean install from the command line
  • Re-import the project into IntelliJ and pay attention when it asks you to enable auto-import

IntelliJ 2016 Update:

The Import Maven Projects automatically setting has been moved to Build, Execution, Deployment > Build Tools > Maven > Importing in your IntelliJ preferences.

Alonso Dominguez's user avatar

Fix before IntelliJ 14

File [menu] -> Settings -> maven -> importing and uncheck «use maven3 to import project»

Fix IntelliJ 15+

Ran into this again, with IntelliJ 15 this time, which has no «use maven3 to import» option available anymore. The cause was that sometimes IntelliJ «doesn’t parse maven dependencies right» and if it can’t parse one of them right, it gives up on all of them, apparently. You can tell if this is the case by opening the maven projects tool window (View menu -> Tool Windows -> Maven Projects). Then expand one of your maven projects and its dependencies. If the dependencies are all underlined in red, «Houston, we have a problem». enter image description here

You can actually see the real failure by mousing over the project name itself.

enter image description here

In my instance it said «Problems: No versions available for XXX» or «Failed to read descriptor for artifact org.xy.z» ref: https://youtrack.jetbrains.com/issue/IDEA-128846 and https://youtrack.jetbrains.com/issue/IDEA-152555

It seems in this case I was dealing with a jar that didn’t have an associated pom file (in our maven nexus repo, and also my local repository). If this is also your problem, «urrent work around: if you do not actually need to use classes from that jar in your own code (for instance a transitive maven dependency only), you can actually get away with commenting it out from the pom (temporarily), maven project reload, and then uncomment it. Somehow after that point IntelliJ «remembers» its old working dependencies. Adding a maven transitive exclude temporarily might also do it, if you’re running into it from transitive chain of dependencies.»

Another thing that might help is to use a «newer version» of maven than the bundled 3.0.5. In order to set it up to use this as the default, close all your intellij windows, then open preferences -> build, execution and deployment -> build tools -> maven, and change the maven home directory, it should say «For default project» at the top when you adjust this, though you can adjust it for a particular project as well, as long as you «re import» after adjusting it.

Clear Caches

Deleting your intellij cache folders (windows: HOMEPATH/.XXX linux

/.IdeaIC15) and/or uninstalling and reinstalling IntelliJ itself. This can also be done by going to File [menu] -> Invalidate Caches / Restart. . Click invalidate and restart . This will reindex your whole project and solve many hard-to-trace issues with IntelliJ.

Часть 4. Основы Maven

Java-университет

Для начала нужно установить Maven, скачав его по этой ссылке.

Далее необходимо распаковать скачанный архив и установить переменной окружения M2_HOME ссылку на местонахождение распакованного архива. Например, C:\Program Files\maven\

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

Если отобразится информация о версии Maven, Java и т.д., все готово к работе.

Теперь открой IntelliJIDEA и создай новый проект. В первом же окне выбери Maven:

Нажми Next и заполни следующее диалоговое окно:

Далее стандартно создай проект в необходимом месте.

После того, как проект создался, обрати внимание на его структуру:

  • в папке src/main/java содержатся java-классы;
  • в src/main/resources — ресурсы, которые использует наше приложение (HTML-страницы, картинки, таблицы стилей и тд);
  • src/test — для тестов.

Управление зависимостями в Maven

На сайте библиотеки. Если нам нужен Apache Commons IO, переходим на официальный сайт, выбираем вкладку Dependency Information. Здесь есть вся необходимая информация — ее можно просто скопировать и добавить в наш раздел dependencies.

В Maven-репозитории. В поиске введи “apache commons io”, и ты увидишь все доступные версии библиотеки. После выбора нужной, просто скопируй:

и добавь в свой pom.xml.

Виды Maven-репозиториев

Сборка Java-проекта с помощью Maven

  1. clean — удаляются все скомпилированные файлы из каталога target (место, в котором сохраняются готовые артефакты);
  2. validate — идет проверка, вся ли информация доступна для сборки проекта;
  3. compile — компилируются файлы с исходным кодом;
  4. test — запускаются тесты;
  5. package — упаковываются скомпилированные файлы (в jar, war и т.д. архив);
  6. verify — выполняются проверки для подтверждения готовности упакованного файла;
  7. install — пакет помещается в локальный репозиторий. Теперь он может использоваться другими проектами как внешняя библиотека;
  8. site — создается документация проекта;
  9. deploy — собранный архив копируется в удаленный репозиторий.

через командную строку:

используя Intellij IDEA:

Часть 4. Основы Maven - 7

До запуска package выполняются фазы validate, compile, test. Исключение — фаза clean. Ее желательно вызывать перед каждой новой сборкой проекта. Фазы можно перечислить через пробел:

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

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