Установка maven в intellij idea

Установка maven в intellij idea

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.

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

If no project is currently open in IntelliJ IDEA, click Create New Project on the Welcome screen. Otherwise, select File | New | Project from the main menu.

Select Maven from the options on the left.

Specify project’s SDK (JDK) or use the default one and an archetype if you want to use a predefined project template (configure your own archetype by clicking Add Archetype ).

GroupId — a package of a new project.

ArtifactId — a name of your project.

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

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

Click Next .
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 directory and Maven repositories. Also, you can check the archetype properties.

Specify the name and location settings.

Open an existing Maven project

    From the main menu, select File | Open .

Alternatively, click Open on the welcome screen.

In the dialog that opens, select the pom.xml file of the project you want to open.

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.

Add a new Maven module to an existing project

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

In the Project tool window, right-click the project folder and select New | Module . Alternatively, from the main menu, select File| New | Module to open the New Module wizard.

If you used 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 sub modules 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 sub modules.

Create a Maven parent project. IntelliJ IDEA creates a standard Maven layout including an src folder.

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.

In the Project tool window, right-click your project (or from the main menu, click File ) and select New | Module to add a sub project.

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 sub project to the parent POM.

In 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 sub project’s POM.

You can click in the left gutter to quickly open the parent POM from your sub project.
You can also add dependencies to the parent POM that will be inherited by the sub projects.

Open Maven tool window to see that all changes made in the parent POM are reflected in sub projects.

Access the Maven settings

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

    In the Settings/Preferences dialog Ctrl+Alt+S , go to Build, Execution, Deployment| Maven .

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

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

Install the Maven custom version

Download the needed Maven version on your computer.

From the main menu select File | Settings/Preferences | Build, Execution, Deployment |Build Tools | Maven .

On the Maven settings page, in the Maven home directory field, specify the location of the Maven custom version installation.

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.

Читайте также:  Почему айфон разряжается сам по себе

From the main menu, select File | Project Structure Ctrl+Shift+Alt+S .

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.

In the Settings/Preferences dialog Ctrl+Alt+S , go to Build, Execution, Deployment | Maven | Runner .

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.

In the Settings/Preferences dialog Ctrl+Alt+S , go to Build, Execution, Deployment | Maven | Importing .

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.

ANTLR — это генератор парсеров, который позволяет создавать парсер по описанию грамматики на одном из основных языков программирования. Он сам написан на java и прекрасно работает с Java.

1) Поставить Oracle Java JDK и Intellij Idea, (можно пропустить этот шаг, если они уже поставлены), и запустить Intellij Idea

Bвести в поле поиска ANTLR и поставить плагин ANTLR v4 grammar plugin. Возможно, понадобится дополнительный поиск по всем репозиториям.

3) Для Maven проекта добавить в pom.xml или создать новый проект.
в dependencies

4) Далее создам и добавляем вручную файл грамматики с расширением .g4. Имя файла должно совпадать с словом после grammar в первой строчке. Составляется она примерно так: берем то, что нужно парсить, и разбиваем на отдельные токены. Для токенов описываем лексемы, например все английские буквы [a-zA-Z];, все числа [0-9] и т.п.. Для примера взято содержимое примера с официального сайта для файла Hello.g4

5) Далее правой кнопкой мыши кликнуть по второй строчке файла, которая начинается с r и выбрать пункт меню Test Rule r

Внизу откроются окна проверки грамматики. В данном случае, плагин показывает ошибку, скорее всего связанную с тем, что это тестовый пример, однако парсер генерируется. Про это можно почитать здесь https://github.com/antlr/antlr4/issues/118, и пока ее проигнорируем. Но в реальных проектах, надо бы внимательнее обращать внимание на эти ошибки.

6) Кликаем по файлу грамматики правой кнопкой мыши, выбираем пункт меню Configute ANTLR Recoqnizer и генерируем парсер

После этого появится в правом нижнем углу сообщение об успехе

7) Далее снова кликаем по файлу правой кнопкой мыши и выбираем пункт меню Configute ANTLR,

и выходит окно для конфигурирования генерации файлов

В этом окне вводим данные о папке назначения и языке программирования, в нашем случае Java, нужны ли visitor или listener, а также другую требуемую информацию, и нажимаем кнопку ОК

И ANTLR после этого генерирует файлы для распознавания. Тем не менее, хотя выходной каталог указан, часто создается новая папка gen в корне проекта, причем java не распознает эти файлы.

Для того, чтобы java увидела эти файлы, папку нужно либо пометить правой кнопкой мыши «Mark Directory As» на «Generated Sources Root» на папку gen.

И должно получится так:

8) ANTLR сгенерировал такие классы:

Класс HelloParser.java — это описание класса парсера, то есть синтаксического анализатора, отвечающего грамматике Hello:

Класс HelloLexer.java — это описание класса лексера, или лексического анализатора, отвечающего грамматике HelloInit:

Hello.tokens, HelloLexer.tokens — это вспомогательные классы, которые содержат информацию о токенах HelloListener.java, HelloBaseListener.java, HelloBaseVisitor, HelloVisitor — это классы, содержащие описания методов, которые позволяют выполнять определенный действия при обходе синтаксического дерева

9) После этого добавим класс HelloWalker (хотя это класс не обязателен, этот код можно изменить и добавить в Main для вывода информации)

10) И, наконец, класс Main — точка входа в программу

11) Запускаем метод main, и получаем на выходе в консоли успешно отработанный парсинг

> Код проекта выложен здесь

Вы можете помочь и перевести немного средств на развитие сайта

I have a small question about IntelliJ IDEA 11. I just imported a project from subversion — its 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:

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:

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 ?!

Создан 12 июл. 12 2012-07-12 15:06:21 Zaur Guliyev

what do you mean by "automatically"? You must declare all your dependencies in your POM as with any normal Maven project. IntelliJ or other IDE will just download them if they are declared there. – Alonso Dominguez 12 июл. 12 2012-07-12 15:10:55

Читайте также:  Pci контроллер шифрации дешифрации lenovo g50 30

It downloads all dependencies but it doesn’t seem to add all of them to classpath. – Zaur Guliyev 13 июл. 12 2012-07-13 07:59:20

and another problem is that intelliJ shows me red underlined errors only when I open that java file. – Zaur Guliyev 13 июл. 12 2012-07-13 08:00:01

One instance where you get this red line is if you have a SNAPSHOT dependency with a classifier, where a newer version of the dependency without the classifier exists. This is perfectly legal in Maven, but IntelliJ gets confused trying to work out the path to the physical file in your local Maven repository. – RCross 22 ноя. 12 2012-11-22 16:12:59

FYI this can still happen in 15.0.2. Just happened to me. Had to blow away my .iml file and .idea folder and reimport. Incredibly frustrating b/c I spent 2 hours fighting it, and ultimately lost all my carefully crafted run configs. – Kevin Pauli 10 дек. 15 2015-12-10 17:25:52

@KevinPauli no need to remove IDEA project files for that, you could just "Reimport All Maven Projects" under "Maven Projects" tab for manual re-import. – Zaur Guliyev 23 дек. 15 2015-12-23 14:04:19

Most times backup and blowing away your user **.m2 folder** or drill in offending packages and delete/rename and doing a ‘mvn clean install’ does the trick. – DaddyMoe 10 дек. 16 2016-12-10 13:51:03

@KevinPauli I had to live the same. – Pierre Thibault 05 май. 17 2017-05-05 21:51:11

At the end it was an error in a parent pom. – Pierre Thibault 05 май. 17 2017-05-05 22:44:38

22 ответа

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.

Создан 13 июл. 12 2012-07-13 08:59:16 Alonso Dominguez

no success but you can see the updated post.. – Zaur Guliyev 13 июл. 12 2012-07-13 11:17:10

so your solution was to mark the dependencies as exported? that’s weird! I use IntelliJ and Maven a lot and none of my projects (some of them are multi-projects) has the export feature enabled. is that Community Edition or Ultimate? – Alonso Dominguez 13 июл. 12 2012-07-13 11:24:19

Its an Ultimate Edition but the project that I have imported was built on Eclipse — so that .classpath was enabled there but IntelliJ uses .iml — So I think its logical to include these libs for the first time if this project did not have .iml file before.. ?! – Zaur Guliyev 13 июл. 12 2012-07-13 11:40:23

oh, ok — did you tried to import it as a Maven project rather than an Eclipse one? I’m used to not check in IDE related files into my source repositories when working with Maven projects: if it’s a Maven project, then Maven rules – Alonso Dominguez 13 июл. 12 2012-07-13 11:58:08

Oh that made sense 🙂 imported them as Maven.. Thanks Alonso! – Zaur Guliyev 13 июл. 12 2012-07-13 13:08:24

I already had this setting, but for some reason a couple of POM files were ignored under Ignored Files. Thank you for pointing me in the right direction! – Martin Andersson 03 фев. 13 2013-02-03 16:04:30

thx a lot it fixed my problem, was trying to fix from last 2-3 hours – coure2011 25 апр. 13 2013-04-25 19:37:37

You can enable Auto import in preferences/setting. Open preferences/setting and search for "Import maven projects automatically". it is under Build,Execution,Deployment>Build Tools>Maven>Importing – Seyed Jalal Hosseini 30 янв. 16 2016-01-30 02:15:48

As far as I can tell, none of the settings mentioned in this answer/comments are available in IntelliJ 2016 community edition. – Justin Blank 26 ноя. 16 2016-11-26 01:04:01

@JustinBlank not surprised by that, given that this is an answer from 2012. The settings are still there, they just have been moved somewhere else (answer has been updated). – Alonso Dominguez 03 фев. 17 2017-02-03 10:48:01

Bug still remains in 11.2017, mvn clean install fixed the bug. Eclipse never had these straight forward bugs – vikramvi 09 ноя. 17 2017-11-09 13:04:30

Читайте также:  Как отправить картинку в смс

Try to Re-Import the project from the Maven Projects panel in IntelliJ IDEA. It should download and configure all the dependencies defined in your pom.xml automatically.

If download doesn’t work from IDEA for some reason, try mvn install from the command line and see if the dependencies can be fetched.

Of course all the required dependencies and any custom repositories must be defined directly in the pom.xml file.

Создан 12 июл. 12 2012-07-12 15:17:20 CrazyCoder

When you create a new project you simply need to choose the option:

.
Import project from external model
Create IDEA project structure over existing external model (Eclipse, Maven. )
.

You’ll find it pretty straight forward from there.
And in your case you can close your project and simply create a new one. Choose your project’s directory, which will override it, making it a Maven project.

Создан 12 ноя. 12 2012-11-12 19:06:43 Markus Coetzee

Agreed. It’s almost certain the OP simply wrongly imported the project. – kaqqao 07 фев. 13 2013-02-07 10:51:46

Importing Maven dependencies may not work if you import the same path several times. This may happen automatically after importing an existing maven project. I can’t figure out why this happens, so I’m inclined to think it is a bug.

For example, if my project is

the three paths may be imported as top nodes:

If such is the case, the dependencies appear to be right, but they won’t be used until you remove the superfluous paths (in this case, src/main and src/test ). Once you do this, refresh and click Build > Rebuild Project. IDEA will pick up the dependencies.

A symptom of this problem is that IDEA warns you of a duplicated path when you manually check a library (second screenshot in the question).

There are several ways to re-read the dependencies in case you need it. If you go to the “Maven Projects” tab, there is a “Reimport All Maven Projects” icon at the top left of the tab. If you suspect IDEA became confused you can click on File > Invalidate Caches.

Создан 24 фев. 13 2013-02-24 08:58:23 Jano

Go into your project structure, under project Settings, Modules, select the dependencies table. For each dependency, change the scope from ‘Test’ to ‘Compile’.

Создан 21 фев. 14 2014-02-21 20:48:38 Bud

If certain maven modules are not compiling check if their pom.xml is on the "ignored files" list. In IntelliJ goto

preferences -> project settings -> maven -> ignored files

and check if the related pom.xml is ignored.

Создан 18 июн. 14 2014-06-18 09:07:24 Udo

Thought I’d throw my $0.02 in here: For me, the fix to this was to go to

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

Update: 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".

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

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.

Other things that might help: deleting your intellij cache folders (windows: HOMEPATH/.XXX linux

/.IdeaIC15) and/or uninstalling and reinstalling IntelliJ itself. GL!

Создан 22 июл. 14 2014-07-22 16:25:20 rogerdpack

Ссылка на основную публикацию
Усики для автомобильной антенны
Убираясь в бардачке я наткнулся на ремкомплект антенных усиков — лежит наверно уже полгода, всё наклеить не могу, то забываю,...
Телефонный шлюз что это
VoIP-шлюз — это межсетевой шлюз, предназначенный для перевода трафика между сетями различных типов. VoIP-шлюзы можно разделить на многоканальные и одноканальные:...
Телефонная клавиатура на компьютере
Виртуальная клавиатура выручит Вас, когда выйдет из строя основное физическое устройство ввода, полностью или частично ( поломается несколько клавиш )....
Усиление сигнала интернета на даче своими руками
С наступление дачного сезона, я озадачился установкой хорошего скоростного интернет на даче, у нас голосовая связь работает без проблем, а...
Adblock detector