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.
Open the pom.xml file in your project root directory.
From the main menu, select Dependency.
Alt+Insert and then selectIn 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>Click 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
This defines the data model for your Spring application. The application will create and store Customer
objects that have an ID, a first name, and a last name.
Create the Customer.java file under /src/main/java/com/example/demo/.
In the Project tool window, select the /src/main/java/com/example/demo/ directory and then select from the main menu (or press Alt+Insert and select Java Class ). Select Class and type the name of the class:
Customer
.Modify the default template or replace it with the following Java code:
package com.example.demo; 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 theCustomer
class is a JPA entity that should be translated into a corresponding table in the database. IntelliJ IDEA designates it with in the gutter.The
@Id
annotation indicates that theid
field is the object's ID. IntelliJ IDEA designates it with in the gutter. The@GeneratedValue
tells JPA that the ID should be generated automatically.
Create a repository interface
Spring Data JPA creates a repository implementation from this interface at runtime.
Create the CustomerRepository.java file under /src/main/java/com/example/demo/.
In the Project tool window, select the /src/main/java/com/example/demo/ directory and then select from the main menu (or press Alt+Insert and select Java Class ). Select Interface and type the name of the interface:
CustomerRepository
.Modify the default template or replace it with the following Java code:
package com.example.demo; import org.springframework.data.repository.CrudRepository; public interface CustomerRepository extends CrudRepository<Customer, Integer> { Customer findCustomerById(Integer id); }This repository works with
Customer
entities andInteger
IDs. It also declares thefindCustomerById()
method. Spring Data JPA will derive a query based on this method's signature, which will select theCustomer
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, theCustomer
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.
Create the DemoController.java file under /src/main/java/com/example/demo/.
In the Project tool window, select the /src/main/java/com/example/demo/ directory and then select from the main menu (or press Alt+Insert and select Java Class ). Select Class and type the name of the class:
DemoController
.Modify the default template or replace it with the following Java code:
package com.example.demo; 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 theDemoController
class as a request handler (a REST controller). IntelliJ IDEA designates it with in the gutter, which you can click to navigate to the corresponding Spring bean declaration.The
@Autowired
annotation tells Spring to inject thecustomerRepository
bean, which is implemented from the repository interface. IntelliJ IDEA designates it with in the gutter, which you can click to navigate to the corresponding autowired dependency.The
@PostMapping("/add")
annotation maps theaddCustomer()
method to POST requests for/add
.The
@RequestParam
annotations map the method parameters to the corresponding web request parameters.The
@GetMapping("/list")
annotation maps thegetCustomers()
method to GET requests for/list
.The
@GetMapping("/find/{id}")
annotation maps thefindCustomerById()
method to GET requests for/find/{id}
.The
@PathVariable
annotation maps the value in place of theid
variable from the URL to the corresponding method parameter.
IntelliJ IDEA designates the web request methods with in the gutter, which you can click to execute the corresponding request.
Run your application and execute requests
Press Shift+F10 or use the icon in the gutter to run your application.
By default, IntelliJ IDEA shows your running Spring Boot application in the Run tool window.
The Console tab shows the output of Spring log messages. By default, the built-in Apache Tomcat server is listening on port 8080.
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.Open DemoController.java and click in the gutter next to the
addCustomer()
method.In the request file, compose the following POST request:
### POST http://localhost:8080/add?first=Homer&last=SimpsonClick 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 Saved new customer! Response code: 200; Time: 217ms; Content length: 19 bytesOpen the HTTP requests file again and compose a GET request to fetch all customers:
### GET http://localhost:8080/listIntelliJ IDEA provides completion suggestions for the request method and body, locations, and available endpoints.
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:
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.
Open the pom.xml file in your project root directory.
From the main menu, select Dependency.
Alt+Insert and then selectIn 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>Click in the popup or press Ctrl+Shift+O to load the updated project structure.
Restart your Spring application and open the Endpoints tab in the Services tool window.
Open the Health tab to monitor the status of your application.
Open the Mappings tab to interact with request mapping endpoints.
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 ( ).
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.
Open the pom.xml file in your project root directory.
From the main menu, select Dependency.
Alt+Insert and then selectIn 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>Click in the popup or press Ctrl+Shift+O to load the updated project structure.
From the main menu, select DemoApplication configuration.
and select theSet both the On 'Update' action and On frame deactivation options to Update classes and resources and click OK to apply the changes.
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 application Ctrl+F10 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. How to add a home page is explained in the Tutorial: Create your first Spring application.
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>Open your web browser and go to http://localhost:8080/. If necessary, refresh the page to make see the new home page.
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.
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.