Add framework support нет maven
6. Providing testing support with Maven
Testing is always an integral part of a project. In Spring, we have a dependency for the libraries that we can test our application as well. Its dependencies are defined as:
Let’s look what all libraries contain with its dependency tree:
Spring Testing Dependency Tree
Even this is all the test dependency we need right now, we will look at two most commonly used test libraries used in Spring Framework here, JUnit and Mockito.
Manually add a facet to a module
In the Project tool window Alt+1 , right-click the module to which you want to add a facet, and select Add Framework Support .
Select the necessary framework from the list.
Depending on your choice, you might be prompted to configure additional settings (for example, to configure a library).
Apply the changes and close the dialog.
Disable framework auto-detection
By default, auto-detection is enabled for all the supported frameworks. You can disable framework auto-detection completely, or exclude individual frameworks from auto-detection.
From the main menu, select File | Project Structure ( Ctrl+Alt+Shift+S ) and select Facets .
Select Detection and click Alt+Insert .
From the Framework to Exclude list, select the necessary option.
You can disable auto-detection of a specific framework only in one directory or in the whole project. The list also allows you to disable auto-detection of all frameworks in a specific directory.
If you want to disable auto-detection of all frameworks in the whole project, deselect the Enable framework detection checkbox.
To re-enable auto-detection everywhere, select the Enable framework detection checkbox and remove all entries from the Exclude from detection list.
I found a pretty old post with this question but unfortunately he didn't get any help. I hope someone can assist me.
I created a repo at GitHub. After cloning it to my computer I tried to add the following framework support: Maven, JSF, EJB, CDI, etc. I know I could add the files manually. But, I want to use what the IDE has to offer.
However, the only framework showing up is SQL, which is different from this post from stackoverflow and from their documentation. Has anyone had this same problem and got it working?
There's a difference between whether you're importing a project based on a Maven pom.xml versus creating a new project and letting Intellij guess at frameworks by scanning your code base. What are the steps that you have taken to create this project? What is the Github link? Please share the pom.xml
You're doing the wrong thing. Start with Maven, and open the pom. If you start with IntelliJ your project is only useful to you -- ever.
@Kirby: as it didnt work I didnt push my branches back to GitHub, but I firstly cloned the repo and added a new Maven Project from it by adding the pom.xml file and setting the project as a Maven one. Then I tried to add frameworks from the IDE but it only showed SQL.
@EngineerDollery: that's basically what I've done but instead of adding dependencies to the pom.xml file I tried to add frameworks directly in the IDE hoping that it would work somehow on my pom.xml file too.
10. Project: Hello World
Just as a simple demonstration for Spring MVC, we will show how a simple controller can be made with Spring MVC 5. For this, we used the dependencies we mentioned in Spring MVC section along with some Servlet Container dependencies. Here are a list of all the dependencies we used in the project:
To configure a front Controller in the project, we will sub-class the AbstractAnnotationConfigDispatcherServletInitializer class:
Now we need to make a Root configuration class which will be emptry as we aren’t configuring any beans in the project for now:
To make this project as a MVC project, we need to make a WebMvcConfigurer class which also marks itself with @EnableWebMvc annotation. This enables the MVC nature of the project:
Once we’re ready with the configuration of the project, we can now add a Controller as a final step. To demonstrate, we will make a simple GET API which just returns a String as “Hello World”:
When we run this project, we’ll see a simple message in our browser. Open the URL we configured, which is:
We will see the following output:
Spring MVC Hello World
For a detailed explanation of why the configuration classes were needed, read Spring MVC Tutorial.
Поговорим о Мавене
Сперва его нужно установить. Разумеется так как у меня мак, показать установку я смогу только для мака. Только вот незадача. Я его давно уже установил, поэтому вам придется сделать это самостоятельно :)Инструкция по установке Maven есть в этом материале. |
2. Project Setup
We will be using one of the many Maven archetypes to create a sample project for our example. To create the project execute the following command in a directory that you will use as workspace:
Creating Sample Project
If you are running maven for the first time, it will take a few seconds to accomplish the generate command because maven has to download all the required plugins and artifacts in order to make the generation task.
Spring Maven Project Setup
Notice that now, you will have a new directory with the same name as the artifactId inside the chosen directory. Now, feel free to open the project in your favourite IDE. Also, this project is only required to demonstrate various dependency tree made when we add appropriate Spring dependencies.
Finally, instead of using an IDE to make this project, we used a simple maven command. This helps us to make project setup and initialisation free from any specific IDE you may use.
4. Spring Persistence Maven Dependencies
Now, let’s look at the core dependencies which are needed for Spring Persistence implementations:
When we look at the dependency tree for this library, we will observe that JDBC and Transaction support is also included in this dependency:
Spring Persistence Dependency Tree
Зачем нам Мавен
- • подтянуть все необходимые библиотеки (в терминах инструментов для сборки — зависимостей (то есть dependency));
- • определить то, как именно нужно собирать проект и во что (например, хотим мы собирать в WAR или JAR или executable JAR);
- • задать версию проекта в одном месте так, чтобы при сборке была указана она;
- • описать проект и его жизненный цикл;
- • добавлять так называется плагины (калька с английского слова Plugin);
- • публиковать библиотеки в общем хранилище, чтобы другие проекты смогли подтянуть их как зависимости.
12. Download the Source Code
This lesson explained how we can use Maven Dependencies for Spring Framework and present sepcific use-cases by keeping the dependencies separate and modular.
Last updated on Apr. 29th, 2021
(+2 rating, 2 votes)
You need to be a registered member to rate this.
3. Spring Dependencies with Maven
Due to a highly modular nature of Spring Framework, adding one dependency doesn’t create a requirement for another dependency. For instance, the Spring Context dependency doesn’t need any Spring MVC dependency or Spring Data libraries. Due to this, we will cover each of the dependencies in their own, separate sections.
To add the Spring Context support, here is the dependency which is needed:
Note that we have used the latest available Spring version which was released at the time this post was published. Again, the latest versions of all the libraries we use can be found on the Maven Central.
To understand all the dependencies which are added to the project when we add a specific dependency, we can run a simple Maven command which allows us to see a complete Dependency Tree for the project. Here is the Maven command which we can use to achieve the same:
Check Dependency Tree
When we run this command, it will show us the following Dependency Tree:
Spring Context Dependency Tree
The spring-context library bring the actual Spring Injection Container into the project and needs few more JARs like spring-aop , spring-beans , spring-core , spring-expression and spring-jcl . When we ran the command above, before presenting to us the Dependency Tree, maven first downloaded the JARs again to confirm if something has changed.
Note that if one of the dependency needed another dependency to run, it was also downloaded and was shown as a sub-branch of the tree in the dependency tree above. The method of sub-branched representation of an indirect dependency clears out when some dependency brings another dependency into the dependency pool of the build system.
Finally, spring-context dependency we added here is runtime scope. This is because this JAR is only needed at runtime to provide Spring related classes only and not used in the project directly, at least not used for simple projects.
2 Answers 2
Intellij reacts to changes in your Maven pom.xml file. Maven does not react to changes in your IntelliJ project module settings.
The steps that you should follow here are
- Close IntelliJ
- In a command shell, clone your Github repository.
- Using an editor external to IntelliJ such as VI or Notepad, create a pom.xml in the root directory. Better yet, use a Maven Archetype to generate your pom.xml .
- Now open IntelliJ. Choose File, New, Project From Existing Sources. Navigate to your pom.xml and follow the prompts.
- I recommend checking Search for projects recursively and Import Maven projects automatically.
- Finish the project creation.
- Now, add dependencies to your pom.xml via the dependencies tag. See Maven Dependencies. Intellij will automatically react to dependencies that you add as long as it can see a Maven Repository on your local machine or on your network or on the Internet.
In this post, we shall demonstrate how to use Maven dependencies for Spring framework for very specific use-cases. The latest versions of all the libraries we use can be found on the Maven Central.
Create an executable JAR
You can conclude the following optional steps to create an executable JAR.
Click to build project. IntelliJ IDEA generates target folder. Note that IntelliJ IDEA only compiles sources and doesn't create either JAR file or Manifest file.
Create a Manifest file in the resources directory.
Right-click the directory, select New | Directory to create the META-INF subdirectory. Then right-click the subdirectory, select New | File to create the MANIFEST.MF file.
In your POM specify the Manifest file information, so you can use Maven to generate an executable jar file.
In the Maven tool window, in the Lifecycle list, double-click the install command to generate the jar file. IntelliJ IDEA generates the appropriate information in the target folder and an executable JAR in the Project tool window.
You can right-click the generated JAR and select Run to execute the file.
If the existing project contains more than one module, converting such a project into the Maven project becomes quite challenging. In this case we recommend that you create an external POM where you describe your project and open your POM as you would open a regular Maven project.
This information is valid for projects that are built with the native IntelliJ IDEA builder. If you're using a build tool, such as Maven or Gradle, make all changes using the build file.
For developing framework-specific applications, IntelliJ IDEA features facets. Facets contain libraries, dependencies, and technologies, and they provide you with additional UI elements for configuring framework-specific settings.
Note that not all facets are available out of the box. To be able to use some of them, you need to install a plugin for the necessary framework first. Refer to JetBrains Plugin Repository for more information on existing plugins.
IntelliJ IDEA can identify a file or a directory that is typical for a certain framework, and add the necessary facet for you. Once the facet is detected and added, IntelliJ IDEA will inform you about the missing configuration and will suggest the necessary actions.
If a facet is not detected automatically, you can add it manually. You can add more than one facet to a module.
Some frameworks are available only in IntelliJ IDEA Ultimate. Refer to comparison matrix to make sure your version of IntelliJ IDEA supports the necessary frameworks.
You can find all facets that are configured for modules in your project in the Project Structure dialog: from the main menu, select File | Project Structure ( Ctrl+Alt+Shift+S ) and select Modules .
If you use a build tool in your project, such as Maven or Gradle, make all changes using the build file.
7. Spring Security Maven Dependencies
Maven dependencies related to Spring Security support are discussed in detail in the Spring Security with Maven lesson.
11. Conclusion
In this post, we talked about various Maven Dependencies related to Spring Framework which makes things crystal clear about the modularity of each dependency and how they’re independent of each other. This lesson is an excellent starting point to understand the required dependencies. We studied several parts of the Spring Framework dependencies and dependencies for JUNit and Mockito as well, even though they aren’t part of the Spring Framework itself but are often used with Spring-based projects to provide extensive Testing support for various layers of Spring Framework.
Finally, we learned how we can show a dependency tree of a project by using a simple maven command and observe which dependencies of a project depends on what other dependencies.
5. Spring MVC Maven Dependencies
Spring MVC Maven dependency is the main dependency you will use when you start to work on Web projects with Spring. Here is the maven dependency to setup Spring MVC in your project:
This is one of the most used dependencies in Spring Framework Maven dependency family. Let’s look at the dependency tree for the spring-web and spring-webmvc library now:
Spring MVC Dependency Tree
The spring-web library contains most common web utilities for a Servlet Environment. The second library, spring-webmvc brings the MVC support for the Servlet Environment.
Maven lifecycle
- • compile — компилировать проект. Это первый этап: в ходе него можно посмотреть, нет ли ошибок компиляции в проекте. Иногда бывает разная чехарда с работой в IDEA, из-за чего появляются проблемы с компиляцией там, где их не должно быть. Так что эта команда расставит все точки над i.
- • test — запускает все тесты, которые работают над JUnit и находятся там, где их ожидает Мавен ( src/test/java ваш капитан).
- • package — это следующая команда, которая включает две предыдущие: то есть, внутри нее вначале запускается команда compile , потом на скомпилированный проект натравливается команда test , ну и если все ок и здесь, запускается создание архива (того архива, который мы выбираем в ))
- • install — когда мы устанавливаем Мавен на машину, у нас появляется локальный гит-репозиторий, в котором хранятся библиотеки, которые мы скачиваем для проектов. Но прелесть Мавена заключается еще и в том, что мы при помощи команды install можем добавить наш проект в локальный гит-репозиторий и локально использовать наш проект как зависимость. Не верите? Попробуйте :) Таким образом можно достаточно быстро посмотреть, как будет выглядеть ваш проект как зависимость у другого.
- • deploy — это венец всего, что было до этого. Команда, которая дарит возможность добавлять проект не только в локальный репозиторий как install, но и на удаленный, откуда каждый человек с доступом сможет использовать его как зависимость.
- • verify — команда, которая все проверит и скажет, готов ли проект к деплою.
- • clean — разумеется, скомпилированные файлы и архив где-то должны храниться. Для этого у Мавена есть папка target . Это данные, которые проекту не нужны. И перед тем, как собирать проект заново, хорошо бы удалить все, что было до этого. Вот для этого и служит команда clean .
Maven Plugins
Хотел еще поговорить о плагинах, но статья и так уже вышла большая. Будет вам домашним заданием. Разберитесь, что это такое и как этим пользоваться. В продолжении статьи разберемся с Maven на практике.
You can open an existing non-Maven project and add a Maven support via IntelliJ IDEA UI.
8. Using JUnit with Maven
To add JUnit dependency in your Spring based project, just add a simple dependency with test scope:
Let’s look what all libraries contain with its dependency tree:
JUnit Dependency Tree
JUnit brings along the Hamcrest library with it too. To use Hamcrest matchers in JUnit, we use the assertThat statement followed by one or several matchers. To read about the available matchers in Hamcrest, read Hamcrest matchers tutorial.
1. Introduction
Understanding how Maven dependencies work and how they are managed, is important in a project for an effective build cycle and the clear concepts about what versions match between various libraries we use in our project. This is due to the reason that we often repeat the set of dependencies in multiple projects. When we don’t understand why we’re using a specific library version, we are ought to do mistakes. Let’s understand the relationship between different Spring Framework dependencies.
pom.xml всему голова
- • groupId — это идентификатор девелоперской организации или отдельного инженера. Обычно это домен в обратном порядке. Для примера здесь описан аккаунт romankh3 на гитхабе. Это очень важно. Скажем, у Spring экосистемы это com.springframework . Так можно отличить оригинальный проект от чьего-то ответвления или просто по совпадению имени проекта.
- • artifaceId — это уже имя конкретного проекта, который описывается в этом помнике.
- • version — версия этого проекта. Здесь все ясно, как божий день: добавил новый функционал, починил старый, отрефакторил или сделал какие-то еще изменения — версию увеличил.
- • packaging — здесь мы описываем, как Мавен должен собирать наш проект. То ли в Jar, то ли в War, то ли еще какие-то другие.
- • name — здесь уже более приятное для глаз название проекта.
Add Maven support
Open an existing project, for example, a Java project.
In the Project tool window, right-click your project and select Add Framework Support .
In the dialog that opens, select Maven from the options on the left and click OK .
IntelliJ IDEA adds a default POM to the project and generates the standard Maven layout in Project tool window.
IntelliJ IDEA also creates a corresponding structure with Lifecycle and Plugins in the Maven tool window.
Open the generated POM and specify a groupId . The artifactId and version are specified automatically.
Every time you change the POM, IntelliJ IDEA displays a popup suggesting to import your changes.
At this point you can further develop your project using Maven. We recommend making all your project changes in POM since IntelliJ IDEA considers pom.xml as a single source of truth.
9. Using Mockito with Maven
Mockito is one of the most widely used Java Testing Dependency which can be used to mock objects and their behaviour as well:
Let’s look what all libraries contain with its dependency tree:
Mockito Dependency Tree
Читайте также: