IntelliJ IDEA 2021.2 Help

Tutorial: Explore Spring support features

This tutorial expands on Tutorial: Create your first Spring application to show how IntelliJ IDEA can help you write code, analyze your Spring application, and manage it at runtime. The tutorial assumes that you start with a simple Spring Boot Maven project generated with Spring Intializr. It should already have the Spring Boot Starter Web dependency for building web applications.

This tutorial guides you through steps that cover the following:

  • Add dependencies for JPA and H2 that enable your Spring application to store and retrieve relational data

  • Write and examine your code

  • Run your application and execute HTTP requests

  • Add Spring Boot Actuator for advanced health monitoring and endpoint analysis

  • Add Spring Boot Developer Tools for faster application updates

Add dependencies for JPA and H2

The Spring Data JPA module provides support for data access using the Java Persistence API (JPA).

H2 is a fast in-memory SQL database written in Java.

  1. Open the pom.xml file in your project root directory.

    The pom.xml file in the project root directory
  2. With the pom.xml file open in the editor, from the main menu, select Code | Generate… Alt+Insert and then select Dependency.

  3. In the Maven Artifact Search dialog, find and add the necessary Maven dependencies:

    • org.springframework.boot:spring-boot-starter-data-jpa

    • com.h2database:h2

    Alternatively, you can add these dependencies to pom.xml manually:

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency>
  4. Click The Load Maven Changes button in the popup or press Ctrl+Shift+O to load the updated project structure.

Create a JPA entity that will be stored in the database

To define the data model for your Spring application, create a JPA entity. The application will create and store Customer objects that have an ID, a first name, and a last name.

  1. Create the Customer.java file under src/main/java/com/example/springboottutorial.

    In the Project tool window, select the src/main/java/com/example/springboottutorial directory and then select File | New | Java Class from the main menu (or press Alt+Insert and select Java Class). Select Class and type the name of the class: Customer.

  2. Modify the default template or replace it with the following Java code:

    package com.example.springboottutorial; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String firstName; private String lastName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }

    The @Entity annotation indicates that the Customer class is a JPA entity that should translate into the corresponding table in the database. IntelliJ IDEA designates it with The Entity icon in the gutter.

    The @Id annotation indicates that the id field is the object's ID. IntelliJ IDEA designates it with The ID icon in the gutter. The @GeneratedValue tells JPA that the ID should be generated automatically.

Create a repository interface

Spring Data JPA will create a repository implementation from this interface at runtime.

  1. Create the CustomerRepository.java file under src/main/java/com/example/springboottutorial.

    In the Project tool window, select the src/main/java/com/example/springboottutorial directory and then select File | New | Java Class from the main menu (or press Alt+Insert and select Java Class). Select Interface and type the name of the interface: CustomerRepository.

  2. Modify the default template or replace it with the following Java code:

    package com.example.springboottutorial; import org.springframework.data.repository.CrudRepository; public interface CustomerRepository extends CrudRepository<Customer, Integer> { Customer findCustomerById(Integer id); }

    This repository works with Customer entities and Integer IDs. It also declares the findCustomerById() method. Spring Data JPA will derive a query based on this method's signature, which will select the Customer object for the specified ID. You can try adding other methods to see how IntelliJ IDEA provides completion suggestions based on available JPA entities (in this case, the Customer class).

Create a web controller

A controller handles HTTP requests for your Spring application. The application will use the /add endpoint to add Customer objects to the database, the /list endpoint to fetch all Customer objects from the database, and the /find/{id} endpoint to find the customer with the specified ID.

  1. Create the DemoController.java file under /src/main/java/com/example/springboottutorial/.

    In the Project tool window, select the /src/main/java/com/example/springboottutorial/ directory and then select File | New | Java Class from the main menu (or press Alt+Insert and select Java Class). Select Class and type the name of the class: DemoController.

  2. Modify the default template or replace it with the following Java code:

    package com.example.springboottutorial; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController public class DemoController { @Autowired private CustomerRepository customerRepository; @PostMapping("/add") public String addCustomer(@RequestParam String first, @RequestParam String last) { Customer customer = new Customer(); customer.setFirstName(first); customer.setLastName(last); customerRepository.save(customer); return "Added new customer to repo!"; } @GetMapping("/list") public Iterable<Customer> getCustomers() { return customerRepository.findAll(); } @GetMapping("/find/{id}") public Customer findCustomerById(@PathVariable Integer id) { return customerRepository.findCustomerById(id); } }

    Here is what each Spring annotation means:

    • The @RestController annotation marks the DemoController class as a request handler (a REST controller). IntelliJ IDEA designates it with The Java Bean icon in the gutter, which you can click to navigate to the corresponding Spring bean declaration.

    • The @Autowired annotation tells Spring to inject the customerRepository bean, which is implemented from the repository interface. IntelliJ IDEA designates it with The autowired dependencies icon in the gutter, which you can click to navigate to the corresponding autowired dependency.

    • The @PostMapping("/add") annotation maps the addCustomer() method to POST requests for /add.

    • The @RequestParam annotations map the method parameters to the corresponding web request parameters.

    • The @GetMapping("/list") annotation maps the getCustomers() method to GET requests for /list.

    • The @GetMapping("/find/{id}") annotation maps the findCustomerById() method to GET requests for /find/{id}.

    • The @PathVariable annotation maps the value in place of the id variable from the URL to the corresponding method parameter.

    IntelliJ IDEA designates the web request methods with The web request mapping icon in the gutter, which you can click to execute the corresponding request.

Run your application and execute requests

  1. Press Shift+F10 or use the Run icon in the gutter of the SpringBootTutorialApplication.java file to run your application.

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

    The Run tool window with a running Spring Boot application

    The Console tab shows the output of Spring log messages. By default, the built-in Apache Tomcat server is listening on port 8080.

  2. Open a web browser and go to http://localhost:8080/list. You should see your application respond with an empty list [ ] because you don't have any customers in the database.

    To add customers, you need to send a POST request to the /add endpoint with request parameters that specify the first and last name. IntelliJ IDEA has an HTTP client built into the editor to compose and execute HTTP requests.

  3. Open DemoController.java and click The Open in HTTP Request Editor icon in the gutter next to the addCustomer() method.

  4. In the request file, compose the following POST request:

    ### POST http://localhost:8080/add?first=Homer&last=Simpson
  5. Click The Run HTTP Request icon in the gutter to execute the request.

    IntelliJ IDEA opens the Run tool window and prints both the request and the response:

    POST http://localhost:8080/add?first=Homer&last=Simpson HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 19 Date: Thu, 28 May 2020 08:10:30 GMT Keep-Alive: timeout=60 Connection: keep-alive Added new customer to repo! Response code: 200; Time: 217ms; Content length: 19 bytes
  6. Open the HTTP requests file again and compose a GET request to fetch all customers:

    ### GET http://localhost:8080/list

    IntelliJ IDEA provides completion suggestions for the request method and body, locations, and available endpoints.

    HTTP request file completion
  7. Execute the GET request to retrieve all of the customers:

    GET http://localhost:8080/list HTTP/1.1 200 Content-Type: application/json Transfer-Encoding: chunked Date: Thu, 28 May 2020 08:23:05 GMT Keep-Alive: timeout=60 Connection: keep-alive [ { "id": 1, "firstName": "Homer", "lastName": "Simpson" } ] Response code: 200; Time: 171ms; Content length: 51 bytes

Try running more POST requests to add other customers. Each one will get a unique ID. Then compose and execute a GET request to return a customer with a specific ID. For example:

### GET http://localhost:8080/find/1

Add Spring Boot Actuator

Spring Boot Actuator adds a number of endpoints that help you monitor and manage your application. This enables IntelliJ IDEA to expose the application's health information and all request mappings available at runtime.

  1. Open the pom.xml file in your project root directory.

  2. From the main menu, select Code | Generate… Alt+Insert and then select Dependency.

  3. In the Maven Artifact Search dialog, find and add the Spring Boot Starter Actuator dependency: org.springframework.boot:spring-boot-starter-actuator

    Alternatively, you can add the dependency manually:

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
  4. Click The Load Maven Changes button in the popup or press Ctrl+Shift+O to load the updated project structure.

  5. Restart your Spring application and open the Actuator tab in the Services tool window.

  6. Open the Health tab to monitor the status of your application.

    Spring Boot Health endpoints tab
  7. Open the Mappings tab to interact with request mapping endpoints.

    Spring Boot Mappings endpoints tab

    By default, it shows all endpoints, including those provided by libraries, such as the Spring Boot Actuator itself. Click the endpoint path to run the corresponding request directly, generate and open it in an HTTP request file to modify and execute when you need it, or open the endpoint URL in a web browser if it's a GET request.

This tab in the Services tool window shows the endpoints available at runtime, not necessarily all request mappings declared in your code. To see the endpoints that are actually declared in your code, use the Endpoints tool window (View | Tool Windows | Endpoints).

Spring tutorial application endpoints

Add Spring Boot Developer Tools

When you make a change in your code, you need to rerun the whole project: shut down the application with all its dependencies, rebuild the code, start the application with the new code. IntelliJ IDEA provides a way to restart just your Spring application context without having to also restart all the external library contexts. This can save time in a large project with a lot of dependencies, especially for debugging and tweaking your code. You can also update static and template resources in a running application.

This functionality is based on the spring-boot-devtools module.

  1. Open the pom.xml file in your project root directory.

  2. From the main menu, select Code | Generate… Alt+Insert and then select Dependency.

  3. In the Maven Artifact Search dialog, find and add the Spring Boot Developer Tools dependency: org.springframework.boot:spring-boot-devtools

    Alternatively, you can add the dependency manually:

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
  4. Click The Load Maven Changes button in the popup or press Ctrl+Shift+O to load the updated project structure.

  5. From the main menu, select Run | Edit Configurations and select the SpringBootTutorialApplication configuration.

  6. Set both the On 'Update' action and On frame deactivation options to Update classes and resources and click OK to apply the changes.

  7. Restart your Spring application.

Your application will work the same, but now whenever you make a change in your source code or resources, you can trigger the updates. Either select Run | Debugging Actions | Update 'SpringBootTutorialApplication' application Ctrl+F10 from the main menu or change focus from IntelliJ IDEA to another application, for example, the web browser. This will update all the classes and resources for your application and restart your application if necessary.

Change the home page

To demonstrate how application updates work, let's expose the /add and /list HTTP endpoints on the home page. For information about adding a home page, see Add a home page.

  1. Open the /src/main/resources/static/index.html file, modify it or replace with the following HTML code:

    <!DOCTYPE HTML> <html> <head> <title>You first Spring application</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <form action="/add" method="POST"> <p>Let's add a customer.</p> <div> <label for="firstName">First name:</label> <input name="first" id="firstName" value="Homer"> </div> <div> <label for="lastName">Last name:</label> <input name="last" id="lastName" value="Simpson"> </div> <div> <button>Add customer</button> </div> </form> <form action="/list" method="GET"> <button>List customers</button> </form> </body> </html>
  2. Open your web browser and go to http://localhost:8080/. If necessary, refresh the page to make see the new home page.

    The new home of your Spring application

    Add some customers and list them. You can also try sending an HTTP request to http://localhost:8080/find/2 to find the customer with ID 2.

  3. You can change the HTML code in index.html, then switch to the web browser and see the changes after you refresh the page.

    You can go even further and install LiveReload so the browser will refresh automatically.

What next?

This covers all the basic features provided by IntelliJ IDEA for Spring development. You can also check out Spring diagrams for an overview of the dependencies in a Spring application and read more specific information about the covered Spring Boot features.

Last modified: 02 August 2022