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

от admin

Gradle

IntelliJ IDEA supports a fully-functional integration with Gradle that helps you automate your building process. You can easily create a new Gradle project, open and sync an existing one, work with several linked projects simultaneously, and manage them.

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

Create a new Gradle project

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.

Name the new project and change its location if necessary.

Select the Create Git repository to place the new project under version control.

You will be able to do it later at any time.

Select a language that you want to use in your project. Click if you want to add other languages available via plugins.

Select Gradle in the list of Build system .

Specify project’s SDK (JDK) or use the default one.

If you don’t have a JDK on your machine, IntelliJ IDEA can quickly download the JDK for you.

The Gradle project sync will wait until the JDK is downloaded.

The selected Add sample code option will create a file with a basic code sample.

Select Gradle DSL . You can select Groovy for traditional syntax or Kotlin as an alternative.

In Advanced Settings , specify the fields which resemble the Maven coordinates. These settings might be helpful if you decide to deploy your project to a Maven repository. The fields you specify are added to the build.gradle file.

GroupId — groupId of the new project. You can omit this field if you plan to deploy your project locally.

ArtifactId — artifactId that is added as a name of your new project.

Version — version of the new project. By default, this field is specified automatically.

For more information on Maven coordinates, see Maven naming conventions.

Create a Java EE project with Gradle as a build tool

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.

Under the Generators section, select Jakarta EE .

Configure your project selecting the appropriate options such as your project’s name, location, language, and select Gradle as your build tool.

IntelliJ IDEA creates a Gradle project with the dedicated Gradle tool window and adds necessary dependencies.

For the more detailed information, refer to Tutorial: Your first Java EE application.

Open an existing Gradle project

If you have the offline mode enabled in your project, the opening or re-importing of the project might fail. To fix the issue, disable the offline mode and re-import your project.

If no project is currently opened in IntelliJ IDEA, click Open on the welcome screen. Otherwise, select File | Open from the main menu.

If you have some custom plugins that require you to import your project from the IntelliJ IDEA model, press Ctrl+Shift+A and search for the Project from Existing Sources action.

In the dialog that opens, select a directory containing a Gradle project and click OK .

IntelliJ IDEA opens and syncs the project in the IDE.

If you need to adjust the Gradle settings options, refer to Gradle settings.

Check Gradle JVM and language level

Gradle JVM : when IntelliJ IDEA opens the Gradle project, it checks the gradle.properties file for the appropriate JVM version specified in org.gradle.java.home and uses it for the project. If it is not specified, then the project SDK is used. Alternatively, you can use the Gradle settings to configure the Gradle JVM.

Language level : the language level settings are applied for a source root or for a module. If a Gradle project has a single linked project then the project default language level is set to the minimum language level among the module language levels. The module language level is set to sourceCompatibility in the build.gradle file.

The preview part is set to the conjunction of preview flags of the module source sets. The source set module language level is set to the corresponding combination of sourceCompatibility property and —enable-preview flag.

Link a Gradle project to an IntelliJ IDEA project

You can have multiple Gradle projects inside one IntelliJ IDEA project. It might be helpful if you keep parts of code in different projects, have some legacy projects on which you need to work, have Gradle composite build or work with microservices. You can link such projects in IntelliJ IDEA and manage them simultaneously.

When you open a Gradle project, the link of the project is established automatically and the Gradle tool window is enabled.

If an IntelliJ IDEA project is not linked to a Gradle project, then the Gradle tool window is disabled. In this case, IntelliJ IDEA displays a message with a link that quickly lets you reimport your Gradle project and enable the Gradle tool window. If the Gradle tool window is active, then you have at least one Gradle project linked.

Open the Gradle tool window.

In the Gradle tool window, click to attach a Gradle project.

In the dialog that opens, select the desired build.gradle file, and click OK .

In the Import Module from Gradle window, specify options for the Gradle project that you are trying to link and click OK .

The project is linked. The Gradle tool window shows the toolbar and a tree view of Gradle entities.

If you need to link back the previously unlinked project, in the Project tool window, right-click the added build.gradle or if it is a Gradle Kotlin module the build.gradle.kts file and select Import Gradle Project .

Add a new Gradle module to an existing Gradle project

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

In a project, from the main menu, select File| New | Module to open the New Module wizard.

If the existing project is not the Gradle project then the process of adding a module is the same as Creating a new Gradle project. If the existing project is a Gradle project then the process of adding a new module is shorter. You need to specify the name of your module in the ArtifactId field. The rest of the information is added automatically and you can use either the default settings or change them according to your preferences. Also, note that Add as module to field, by default, displays the name of your project to which you are trying to add a module. You can click to select a different name if you have other linked Gradle projects.

Convert a regular project into a Gradle project

Open your project in IntelliJ IDEA.

In the Project tool window, right-click the name of your project and select New | File .

In the dialog that opens enter build.gradle and click OK .

Open the build.gradle file in the editor, add the information you need and re-open your project. The following minimal information should be included into the project’s build script file:

As soon as you create a build.gradle file, IntelliJ IDEA recognizes the Gradle build script and displays a notification suggesting to load the project as Gradle. After you load the project, IntelliJ IDEA enables the Gradle tool window.

We also recommend that you add the settings.gradle file to your project and add rootProject.name = ‘projectName’ to it. Where ‘projectName’ would be the name of your project.

Access the Gradle settings

Use the Gradle settings to configure the build and run actions for each linked Gradle project, a Gradle version, importing of the project’s changes, and so on.

In the Settings dialog ( Ctrl+Alt+S ), go to Build, Execution, Deployment| Gradle .

Click on the toolbar, in the Gradle tool window to access the Gradle settings.

On the Gradle settings page, configure the available options and click OK to save the changes.

Configure a Gradle version for a project

IntelliJ IDEA lets you use different options to configure a Gradle version for your Gradle project. You can use the default Gradle wrapper, use a Gradle wrapper as a task, or configure a local Gradle distribution.

Select in the Gradle tool window to quickly access the Gradle settings page.

In the Use Gradle from list select one of the following options:

‘gradle-wrapper.properties’ file : this is a recommended default option that uses Gradle wrapper.

In this case you delegate the update of Gradle versions to Gradle and get an automatic Gradle download for the build. This option also lets you build with a precise Gradle version. The Gradle version is saved in the gradle-wrapper.properties file in the gradle directory of your project and helps you eliminate any Gradle version problems.

‘wrapper’ task in Gradle build script : select this option to configure a Gradle wrapper according to the wrapper task configuration. It might be convenient if you prefer to control which Gradle version to use in the project.

If you used the default Gradle wrapper option and then switched to the Gradle wrapper task configuration, changes you made in the task automatically update during the project import.

Specified location : select this option if you want to manually download and use a specific Gradle version. Specify the location of your Gradle installation and JVM under which IntelliJ IDEA will run Gradle when you import the specified Gradle project and when you execute its tasks.

Click OK to save the changes.

Add VM options for the Gradle project

You can specify VM options for your Gradle project using the gradle.properties file.

Create or open your Gradle project.

In the Project tool window, right-click the project and from the context menu, select New | File .

In the New File dialog, enter gradle.properties as a filename and click OK .

Open the created file in the editor and add the VM options you need.

For more information, refer to the Gradle documentation.

Increase daemon heap size

You can adjust the existing Gradle daemon heap size for your project using the gradle.properties file.

Create or open your Gradle project.

In the Project tool window, right-click the project and from the context menu, select New | File .

Gradle dependencies

IntelliJ IDEA lets you add and manage dependencies in your Gradle project. You can add dependencies, and view them in the diagram.

Generate Gradle dependencies

Any dependency added to the project is managed by Gradle. The best way to add or manage a dependency is in the build.gradle file. Dependencies that you set up manually inside IntelliJ IDEA module settings will be discarded on the next Gradle project reload.

Add a Gradle dependency

Open the build.gradle file in the editor.

Press Alt+Insert to open the Generate context menu.

From the context menu, select Add dependency .

Add dependency

The Dependencies tool window opens.

In the Dependencies 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 .

Search Artifact

For more information on working with the Dependencies tool window, refer to Package Search.

IntelliJ IDEA adds a dependency to the build.gradle file.

Build script: added dependency

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

Gradle tool window and Project tool window

If the added dependency has its own transitive dependencies, IntelliJ IDEA displays them in both tool windows. Besides the transitive dependencies, IntelliJ IDEA also indicates cyclic dependencies in the Gradle tool window.

Gradle tool window: cyclic dependencies

If you add a dependency configuration of the source set, it will be displayed in the Gradle tool window as well.

View dependencies as a diagram

Make sure you have the bundled Diagrams and Gradle Extension plugins enabled. Also, make sure you have the Gradle version 3.3 or later.

You can work with Gradle dependencies in the diagram format. It might be helpful when you have a large project and want to see the whole picture of how dependencies (including the transitive ones) are connected inside the project.

In the Gradle tool window, select a project, on the toolbar, click or select the Show Dependencies option from the context menu.

the Show Dependencies option

You can select the Show Dependecies Popup ( Ctrl+Alt+U ) option to open the graph in a separate window. To close the popup, press Escape .

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

Gradle dependencies diagram

When you navigate to a dependency in a graph, IntelliJ IDEA displays its version, group and artifact IDs.

Use the diagram window toolbar to manage the diagram. You can change the size of a diagram, export it to a file, see only a part of the diagram you are interested in, and so on.

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).

Hold down Alt and move the cursor to zoom in on the parts of the diagram.

In Android and Kotlin projects IntelliJ IDEA supports only the default visibility level.

In the diagram window, select the project and click .

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

Show path from selection to root

You can select dependencies and see how they are connected to the root.

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

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

On the toolbar, click.

Show neighbors of the selected nodes

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.

On the toolbar, click.

Search for a specific dependency in the graph

In the diagram window, press Ctrl+F to open the Diagram Elements popup.

Start typing a name of a dependency you want to find, select the one you need from the list of search results and press Enter . IntelliJ IDEA locates the needed dependency in the graph.

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.

Dependency analyzer

Gradle 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 Gradle tool window, click .

Alternatively, in the Gradle 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 build.gradle , right-click the dependency in the Usages part and select Go to ‘build.gradle’ .

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

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.

Declaring dependencies

Before looking at dependency declarations themselves, the concept of dependency configuration needs to be defined.

What are dependency configurations

Every dependency declared for a Gradle project applies to a specific scope. For example some dependencies should be used for compiling source code whereas others only need to be available at runtime. Gradle represents the scope of a dependency with the help of a Configuration. Every configuration can be identified by a unique name.

Many Gradle plugins add pre-defined configurations to your project. The Java plugin, for example, adds configurations to represent the various classpaths it needs for source code compilation, executing tests and the like. See the Java plugin chapter for an example.

dependency management configurations

For more examples on the usage of configurations to navigate, inspect and post-process metadata and artifacts of assigned dependencies, have a look at the resolution result APIs.

Configuration inheritance and composition

A configuration can extend other configurations to form an inheritance hierarchy. Child configurations inherit the whole set of dependencies declared for any of its superconfigurations.

Configuration inheritance is heavily used by Gradle core plugins like the Java plugin. For example the testImplementation configuration extends the implementation configuration. The configuration hierarchy has a practical purpose: compiling tests requires the dependencies of the source code under test on top of the dependencies needed write the test class. A Java project that uses JUnit to write and execute test code also needs Guava if its classes are imported in the production source code.

dependency management configuration inheritance

Under the covers the testImplementation and implementation configurations form an inheritance hierarchy by calling the method Configuration.extendsFrom(org.gradle.api.artifacts.Configuration[]). A configuration can extend any other configuration irrespective of its definition in the build script or a plugin.

Let’s say you wanted to write a suite of smoke tests. Each smoke test makes a HTTP call to verify a web service endpoint. As the underlying test framework the project already uses JUnit. You can define a new configuration named smokeTest that extends from the testImplementation configuration to reuse the existing test framework dependency.

Resolvable and consumable configurations

Configurations are a fundamental part of dependency resolution in Gradle. In the context of dependency resolution, it is useful to distinguish between a consumer and a producer. Along these lines, configurations have at least 3 different roles:

to declare dependencies

as a consumer, to resolve a set of dependencies to files

as a producer, to expose artifacts and their dependencies for consumption by other projects (such consumable configurations usually represent the variants the producer offers to its consumers)

For example, to express that an application app depends on library lib , at least one configuration is required:

Configurations can inherit dependencies from other configurations by extending from them. Now, notice that the code above doesn’t tell us anything about the intended consumer of this configuration. In particular, it doesn’t tell us how the configuration is meant to be used. Let’s say that lib is a Java library: it might expose different things, such as its API, implementation, or test fixtures. It might be necessary to change how we resolve the dependencies of app depending upon the task we’re performing (compiling against the API of lib , executing the application, compiling tests, etc.). To address this problem, you’ll often find companion configurations, which are meant to unambiguously declare the usage:

At this point, we have 3 different configurations with different roles:

someConfiguration declares the dependencies of my application. It’s just a bucket that can hold a list of dependencies.

compileClasspath and runtimeClasspath are configurations meant to be resolved: when resolved they should contain the compile classpath, and the runtime classpath of the application respectively.

This distinction is represented by the canBeResolved flag in the Configuration type. A configuration that can be resolved is a configuration for which we can compute a dependency graph, because it contains all the necessary information for resolution to happen. That is to say we’re going to compute a dependency graph, resolve the components in the graph, and eventually get artifacts. A configuration which has canBeResolved set to false is not meant to be resolved. Such a configuration is there only to declare dependencies. The reason is that depending on the usage (compile classpath, runtime classpath), it can resolve to different graphs. It is an error to try to resolve a configuration which has canBeResolved set to false . To some extent, this is similar to an abstract class ( canBeResolved =false) which is not supposed to be instantiated, and a concrete class extending the abstract class ( canBeResolved =true). A resolvable configuration will extend at least one non-resolvable configuration (and may extend more than one).

On the other end, at the library project side (the producer), we also use configurations to represent what can be consumed. For example, the library may expose an API or a runtime, and we would attach artifacts to either one, the other, or both. Typically, to compile against lib , we need the API of lib , but we don’t need its runtime dependencies. So the lib project will expose an apiElements configuration, which is aimed at consumers looking for its API. Such a configuration is consumable, but is not meant to be resolved. This is expressed via the canBeConsumed flag of a Configuration :

Управление зависимостями в 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, а также различные фокусы для каждого представления.

Похожие статьи