Как подключить spring в idea


Spring is an application framework for the Java platform. It helps you build modern web applications with support for microservice architectures, cloud systems, reactive processing, and serverless workloads.

IntelliJ IDEA provides extensive coding assistance for Spring, including a dedicated project wizard, code highlighting, intelligent context actions, embedded documentation, navigation, and highly customizable run configurations.

To use Spring in your project, you need the Spring facet that comprises libraries and UI elements for configuring settings specific to Spring. IntelliJ IDEA automatically detects Spring configuration files in your code. The IDE will inform you if the project requires any adjustements and suggest the necessary actions. So normally, manual configuration is not required.

However, if IntelliJ IDEA does not detect configuration files automatically, you can add the facet manually:

Manually add Spring support to existing modules

From the main menu, select File | Project Structure or press Ctrl+Alt+Shift+S to open the Project Structure dialog.

Select Spring from the list.

Select the necessary library.

If you already have a Spring library, select Use library and specify the library that you want to use.

If you have the corresponding JAR files, click Create and select the files to arrange into a new library.

Whatever option you choose, you can click Configure to edit the selected library settings and contents.

When you are done, click OK to add the facet to the module.

Create an application context

The Spring application context is a way of grouping configuration files in IntelliJ IDEA. When you create a context, you let IntelliJ IDEA understand the relationship between configuration files included into this context.

You can create as many application contexts as you need and add any configuration file in more than one context.

From the main menu, select File | Project Structure or press Ctrl+Alt+Shift+S to open the Project Structure dialog.

Читайте также:  Acer iconia tab w700 как подключить клавиатуру

In the New Application Context dialog, specify the name for context, and select the files you want to include in the context.

In some cases, adding an application context is not required. For example, Spring MVC web applications have strict rules about their configuration. Spring support in IntelliJ IDEA can deduce them and create an autodetected application context for you, as well as set up the Web facet.

Configure a parent context

IntelliJ IDEA allows you to configure a parent-child relationship between contexts. Beans from a parent context are visible to beans in child contexts, but not vice versa. Therefore, beans from child contexts can use configuration from the parent context.

For example, Spring MVC applications usually have two contexts: one for the web layer beans and the other for services and repositories. The web layer context will be a child context in this case, as you need to inject services into controllers, not the other way around.

To configure a parent context, use the New Application Context dialog, as described in Create an application context.

IntelliJ IDEA can configure the parent context automatically. For example, if the IDE detects the Spring Cloud context, it will make it a parent application context for Spring Boot.

Change active profiles

If you have defined at least one profile in your project, IntelliJ IDEA will show a special panel on top of the editor. You can use this panel to view the current profile name and change active profiles.

Click Change Profiles on the panel.

Select the component to which you want to map the profile. This can be either the entire project, the current module, or the current context.

Select the profile to which you want to map this component.

Читайте также:  Как подключить двигатель постоянного тока 12в


Создаем Spring Boot Hello World приложение в Intellij IDEA

Самый простой способ создать Spring Boot приложение, на мой взгляд — это воспользоваться официальным сайтом Spring.

Открываем Intellij IDEA и создаем новый Maven проект:

После создания проекта идем на сайт Spring в раздеп Guides:

Далее в строке поиска пишем MVC и получаем такой результат:

Заходим по этой ссылке и делаем все, что там написано (далее по тексту).

Конфигурация pom.xml для Spring Boot

Чтобы сконфигурировать Spring Boot проект нам надо прописать build script:

Создаем файлы проекта Spring Boot

Далее по инструкции создаем пакет hello и в нем класс GreetingController:

Содержимой класса выглядит следующим образом:

Далее в ресурсах создаем папку templates и в ней файл greeting.html, имеющий следующее содержимое:

Далее в пакете hello создадим класс Application:

Далее создаем папку static в ресурсах и в ней создаем файл index.html:

Запуск Spring Boot приложения

Чтобы запустить приложение, надо перейти в класс Application и выполнить действия, показанные на скриншоте:

Наше приложение доступно по адресу

Создание WAR архива Spring Boot приложения и deploy на Apache Tomcat

Чтобы задеплоить написанное приложение на tomcat необходимо выполнить следующие действия:

Класс Application должен приобрести следующий вид:

В файл pom.xml дописываем

после тега version в начале файла.

Далее создаем war архив (View/Tool Windows/Maven Projects):

В проекте создалась папка target и в ней файл war.

Останавливаем проект и запускаем Apache Tomcat.

Заходим в Application List и деплоим наш файл, предварительно переименовав его, как вам удобно:


Tutorial: Create your first Spring application

This tutorial describes how to create and run a Spring application in IntelliJ IDEA. It will be a Spring Boot Maven project generated by Spring Initializr. This is the quickest way to create a Spring application, and IntelliJ IDEA provides a dedicated project wizard for it. You will learn how to expose an HTTP endpoint and map it to a method that returns a greeting to the user when accessed through a web browser.

Читайте также:  Focusrite scarlett 2i2 как подключить к компьютеру

Create a new Spring Boot project

From the Project SDK list, select the JDK that you want to use in your project.

If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.

For this tutorial, select the latest available JDK (version 14 or later).

This dependency is required for any web application that uses Spring MVC.

Add a method that sends a greeting

Spring Initializr creates a class with the main() method to bootstrap your Spring application. In this tutorial, we’ll add the sayHello() method directly to this class.

Add the sayHello() method and the necessary annotations so that the file looks like this:

The sayHello() method takes the name parameter and returns the word Hello combined with the parameter value. Everything else is handled by adding Spring annotations:

The @RestController annotation marks the DemoApplication class as a request handler (a REST controller).

Run your Spring application

By default, IntelliJ IDEA shows your running Spring Boot application in the Run tool window.

This is the default generic response. You can provide a parameter in your web request to let the application know how to greet you properly. For example, try http://localhost:8080/hello?myName=Human.

Add a home page

The created Spring Boot application has one endpoint available at /hello. However, if you open the root context of your application at http://localhost:8080/, you will get an error because there is no root resource defined. Let’s add a static HTML home page with links to your endpoint.

Modify the default template or replace it with the following HTML code: