IntelliJ IDEA 2024.3 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 Initializr. 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, press Alt+Insert and select Add Starters.

  3. In the window that opens, select the Spring Data JPA and H2 Database 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 Sync Maven Changes button in the popup or press Ctrl+Shift+O to sync 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 jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.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.

    All other entity attributes (firstName and lastName in our example) are designated with The ID icon in the gutter. You can use it to quickly open the attribute in Persistence view.

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 in the build-in HTTP client.

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. With the pom.xml file open in the editor, press Alt+Insert and select Add Starters.

  3. In the Add Starters window that opens, select the Spring Boot Actuator dependency.

    Edit Starters

    Alternatively, you can add the dependency manually:

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

  5. Restart your Spring application with The Rerun button or Ctrl+F5 and open the Actuator tab in the Run 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 Actuator tab in the Run 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 | 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. With the pom.xml file open in the editor, press Alt+Insert and select Add Starters.

  3. In the Add Starters window that opens, select the Spring Boot DevTools dependency.

    Alternatively, you can add the dependency manually:

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

  5. In the main menu, go to Run | Edit Configurations and select the SpringBootTutorialApplication configuration.

  6. Under Modify options, 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 more information about adding a home page, refer to 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.

Productivity tips

Quickly inject beans

IntelliJ IDEA provides a number of ways to quickly inject beans, which saves you from having to manually type annotations and fields or constructors.

  1. Within a Spring component, start typing a bean name.

  2. Use one of the following ways to get the needed bean:

    • Press Alt+Enter and select Add dependency with name matching 'bean name'.

    • Start typing a bean name and enter .autowire to invoke the postfix completion template. For example, enter custom.autowire to find beans that start with custom.

  3. If the entered name matches exactly the name of a bean, it will be injected right away. If it matches only a part of the name, you can select the needed bean from the Select Bean window that opens.

    Bean injection

If a class has fields annotated with @Autowire, this will add a new @Autowire field. Otherwise, it will add the corresponding parameter to the class constructor.

Alternatively, you can press Alt+Insert and select the injection type from the Generate context menu: @Autowired Dependency, Constructor Dependency, or Setter Dependency. Unlike the method described above, this method lets you select a way to inject a bean and does not filter the beans, so you can preview all of them.

If you use Spring Security, you may have security rules in place, such as allowing access to URLs for authenticated users only or for users with specific roles. IntelliJ IDEA provides navigation from security matchers to Spring controllers and from controllers to security matchers.

  • To navigate to a controller method from a Spring security matcher, click next to the matcher (such as antMatchers, mvcMatchers, requestMatchers in Spring Security before 5.8 or securityMatcher in Spring Security 5.8 and higher, or in XML URL patterns).

  • To check the security configuration for a controller (and navigate to this configuration if it's available), click next to the controller URL and select Show security configurations for URL.

Spring Security URL mapping

Quickly create a connection to a database

Using the Database Tools and SQL plugin, IntelliJ IDEA lets you create and manage connections to databases.

In a Spring Boot project, you can instantly create it from your application properties file.

  1. Open an application.properties or application.yml file. If it contains datasource-related properties (for example, spring.datasource.url) , the datasource icon Datasource icon will be displayed in the gutter.

  2. Click Datasource icon. This will open the data source creation form with datasource parameters (such as URL, username, or database name) populated based on data from your configuration file.

    If the data source is already configured, the datasource icon is displayed instead. Click it to open the datasource in the Database tool window.

    Create data source window

Below is the list of databases for which this action is available:

  • Amazon Redshift

  • Apache Cassandra

  • Apache Derby

  • Couchbase

  • H2

  • HSQLDB

  • IBM Db2

  • MariaDB

  • Microsoft SQL Server

  • MongoDB

  • MySQL

  • Oracle Database

  • PostgreSQL

  • Redis

  • SQLite

  • Sybase

For more details on data source parameters, refer to Data sources.

What's 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: 24 October 2024