- Using Maven within the Eclipse IDE — Tutorial
- 2. Installation and configuration of Maven for Eclipse
- 2.1. Installation of the Maven tooling for the Eclipse IDE
- 2.2. Configure automatically updates of Maven dependencies
- 3. Exercise: Create a new Maven project via the Eclipse IDE
- 3.1. Create Maven project
- 3.2. Update project to use Java
- 3.3. Update Maven settings in Eclipse
- 3.4. Validate
- 4. Exercise: Adjust generated project to use JUnit5 and external libraries
- 4.1. Change generated project
- 4.2. Update Maven
- 4.3. Update test
- 4.4. Adding dependencies to your project
- 4.5. Use library
- 4.6. Validate
- 5. Exercise: Converting a Java project (create with Eclipse) to Maven
- 5.1. Create Java project
- 5.2. Convert to Maven project
- 5.3. Execute the Maven build
- 6. Exercise: Create a Java web project in Eclipse using Maven
- 6.1. Create Maven web project project
- 6.2. Build your project
- 6.3. Run on the server
- 7. Exercise: Debug tests
- 8. References for Webdevelopment with Eclipse
- Maven проект в Eclipse
- Инсталляция плагина maven
- Создание maven project
Using Maven within the Eclipse IDE — Tutorial
The Eclipse IDE provides support for the Maven build. This support is developed in the M2Eclipse project.
It provides an editor for modifying the pom file and downloads dependencies if required. It also manages the classpath of the projects in the IDE. You can also use wizards to import existing Maven projects and to create new Maven projects.
2. Installation and configuration of Maven for Eclipse
2.1. Installation of the Maven tooling for the Eclipse IDE
Most Eclipse IDE downloads already include support for the Maven build system. To check, use Help About and check if you can see the Maven logo (with the M2E ) sign.
If Maven support is not yet installed, the following description can be used to install it.
To install Maven support, select the Help Install New Software menu entry. To use the latest release, enter the following URL in the Works with field.
https://download.eclipse.org/releases/latest
For the usage of Maven for Java projects, you only need the m2e component.
2.2. Configure automatically updates of Maven dependencies
In most cases it is useful if changes in the Maven configuration automatically updates the project settings.
Therefore, et the Automatically update Maven projects configuration flag under Window Preferences Maven .
3. Exercise: Create a new Maven project via the Eclipse IDE
In this exercise you learn how to create a new Maven project with the Eclips IDE.
3.1. Create Maven project
Create a new Maven project via File New Other… Maven Maven Project .
On the first wizard page, you can select if you want to create a simple project. In this case you skip the archetype selection. In this exercise we want to use an archetype as template for our project creation.
Press next, filter for the «maven-archetype-quickstart» archetype and select the entry with the apache group. This is the classical Maven example archetype for project creation.
On the last tab enter the GAV of your project similar to the following screenshot.
3.2. Update project to use Java
Change the pom file of the generated project to use Java 11. For this copy the following code onto the content via the pom.xml tab of the Maven editor.
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.vogella com.vogella.maven.eclipse 0.0.1-SNAPSHOT com.vogella.maven.eclipse http://www.vogella.com UTF-8 11 11
3.3. Update Maven settings in Eclipse
Right-click your project and select Maven Update Project and update your project.
3.4. Validate
Validate that the Maven build is correctly configured by running the build. For this right-click the pom.xml file and select Run As Maven build .
This opens a dialog which allows to define the parameters for the start. Enter clean verify in the Goals: field and press the Run button.
4. Exercise: Adjust generated project to use JUnit5 and external libraries
In this exercise you adjust your generated project to use JUnit5.
4.1. Change generated project
Change the pom file of the generated project to use JUnit 5. For this copy the following code onto the content via the pom.xml tab of the Maven editor.
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.vogella com.vogella.maven.eclipse 0.0.1-SNAPSHOT com.vogella.maven.eclipse http://www.vogella.com UTF-8 11 11 (1) maven-surefire-plugin 2.22.2 maven-failsafe-plugin 2.22.2 (2) org.junit.jupiter junit-jupiter-api 5.7.2 test org.junit.jupiter junit-jupiter-engine 5.7.2 test
4.2. Update Maven
Right-click your project and select Maven Update Project and update your project.
4.3. Update test
Update your generated test to JUnit 5 via the following:
package com.vogella.maven.eclipse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class AppTest @Test public void shouldAnswerWithTrue() assertTrue( true ); > >
4.4. Adding dependencies to your project
The Eclipse Maven tooling makes adding dependencies to the classpath of your project simple. In can directly add it to your pom file, or use the Dependencies tab of the pom editor.
Switch to the Dependencies tab and press the Add button.
In this example we add Gson as dependency. For this we use the latest GAV which we find via https://mvnrepository.com/artifact/com.google.code.gson/gson
If the Maven index was downloaded you can also search directly this dependency via the dialog.
Right-click your project and select Maven Update Project and update your project.
4.5. Use library
Change or create the App.java class in your src/main/java folder. This classes uses Gson. As Maven added it to your classpath, it should compile and you should be able to start the class via Eclipse.
package com.vogella.maven.lars; import com.google.gson.Gson; public class App public static void main( String[] args ) Gson gson = new Gson(); System.out.println(gson.toJson("Hello World!") ); > >
4.6. Validate
Run the Maven build again and verify that the build runs successfully.
5. Exercise: Converting a Java project (create with Eclipse) to Maven
This exercise demonstrates how to convert a Java project to a Maven project.
5.1. Create Java project
Create a new Java project called com.vogella.build.maven.simple in Eclipse.
Add one class called Main . This class should have a main method, which write «Hello Maven!» to the command line.
package com.vogella.build.maven.simple; public class Main public static void main(String[] args) System.out.println("Hello Maven!"); > >
5.2. Convert to Maven project
Select your project, right-click on it and select Configure Convert to Maven project… .
This creates a pom.xml file similar to the following.
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.vogella.build.maven.simple com.vogella.build.maven.simple 0.0.1-SNAPSHOT src maven-compiler-plugin 3.1 1.8 1.8
5.3. Execute the Maven build
Right-click the pom.xml file and select Run As Maven build .
Enter «clean install» as Goal.
You have to enter the goals manually. The Select… button does not work, the dialog it displays is always empty. |
Press the Finish button. This starts the build, which you can follow in the Console view.
Once the build finishes, press F5 on the project to refresh it. You see a target folder, which contains the build artifacts, e.g., a JAR file.
6. Exercise: Create a Java web project in Eclipse using Maven
This exercise demonstrates how to create a web application in Eclipse which uses Maven. It assumes that you have already configured Eclipse for the creation of web applications.
6.1. Create Maven web project project
Create a new Maven project called com.vogella.javaweb.maven.first via the File New Other Maven Maven Project entry. On the archetype selection, select the maven-archetype-webapp entry and click the Next button.
Enter the group, artifact and version of your new Maven component.
You may see the error: The superclass «javax.servlet.http.HttpServlet» was not found on the Java Build Path. To fix this, right click on your project and select Properties. On the Targeted Runtimes select your web server entry, e.g., Tomcat.
6.2. Build your project
Run your mvn clean verify build command from Eclipse. Validate that there are no issues with the build.
6.3. Run on the server
Right-click your project and select the Run As Run on Server menu entry.
If you open a browser you should be able to access your webapplication.
7. Exercise: Debug tests
Add a breakpoint in Eclipse in one of your tests.
Start your Maven build on the commadline with the debug parameter.
mvn -Dmaven.surefire.debug test
This stop the command line build once the tests are executed and listen on port 5005 for a remote connection.
In Eclipse select the Run Debug Configuration… and create a new Remote Java Application run configuration.
Ensure to enter the correct project and the port 5005. Press the Debug button to connect to the running build. You can now debug your test.
8. References for Webdevelopment with Eclipse
To use Maven in Eclipse for Java web development, you should also install an configure the Eclipse web development tools (WTP). See Eclipse Web Development Tools for a tutorial.
Maven проект в Eclipse
Для интеграции maven в Eclipse есть плагин m2eclipse, позволяющий создавать и импортировать существующие maven-проекты в среду разработки IDE.
Инсталляция плагина maven
Для инсталляции плагина в Eclipse откройте окно «Help>Install New Software» и введите в поле «Work with» строку http://download.eclipse.org/releases/luna. Укажите правильно релиз своей версии Eclipse.
В примере используется Eclipse версии Luna (4.4.2). Для установки в Eclipse плагина maven версии, к примеру, Indigo строка url (Work with) должна выглядеть примерно так : http://download.eclipse.org/indigo.
Выберете и разверните «Collaboration», где Вы увидите плагин m2e — Maven integration for Eclipse. Выделяйте запись и переходите к следующим шагам инсталляции, где можно соглашаться с лицензией и загружать плагин в Eclipse.
Создание maven project
После того, как maven плагин установлен в Eclipse, можно создать project. Для этого необходимо открыть окно мастера создания проектов и выбрать Maven Project.
А вот на этом шаге необходимо выбрать архетип проекта. Выделяем maven-archetype-webapp для создания проекта WEB-приложения.
На последнем шаге определяем GAV-параметры (GroupId, ArtifactId, Version) создаваемого проекта.
В результате мы получаем maven проект WEB-приложения. Таким образом, не прилагая особых усилий, можно создать maven project непосредственно в среде разработки Eclipse.
Структуру созданного проекта с добавлением в него сервлета можно увидеть на странице примеров maven проектов, где рассмотрен другой подход создания архитектуры этого типа приложения — использование команды mvn archetype:generate с опциями. После создания maven проекта из командной строки он был импортирован в Eclipse. Разные подходы с одним и тем же результатом.