Build a simple API service with Spring Boot. Feel the convenience, simplicity and efficiency of Spring Boot.
Development Environment
In tutorial, The software we use is free.
Java: JDK 8
IDE: IDEA 2019 Community
Build Project Skeleton
In Spring Boot Starter, fill in the basic configuration information of the project and the third-party components that need to be used in the project. According to the goal of the experiment, choose maven as the build tool and Java as the Programming language, the version of Spring Boot chooses the current stable version 2.5.2. Third-party package options: Lombok, Spring Web, Spring Data JPA, H2 Database.
Then click the “Generate the Project” button to download the generated project basic package. After downloading, you will get a file named: todo-api.zip, unzip it and enter the todo-api directory. Then use IDEA to open the project directory. Because there is a pom.xml file in the directory, IDEA can detect that this is a maven project and will automatically download the dependent third-party packages. (If you are building a Spring Boot project for the first time, the downloading process may be relatively long)
Create API class
In Spring Boot, building an API is very simple. First create a common Java class, and then define a common method that returns a string in the class. code show as below:
1 |
|
Now, run the program and visit the address localhost:8080/ok, you can see the “ok” is display in browser.
Build entity class Todo
Create a new model package in the project, and then create a simple Java class in it: Todo, add a few basic attributes to the class:
1 | public class Todo { |
In the class, we have neither written get, set methods nor constructors. Because we will use Lombok to generate these.
- If you need to generate get, set methods, add @Data annotations to the class definition
- If you need to generate a constituent function, use the annotation of the corresponding constructor. In this example, we construct a constructor that includes all attributes, then add @AllArgsConstructor
The completed code is as follows:
1 |
|
Retrofit API to return all Todos
Now return to the TodoApi class and add a method to return all Todo lists. The added code is as follows:
1 | "/todo") ( |
Here, we map the method to the URL “/todo” and construct Todo data for two examples. If the error “Todo does not specify the composition method” appears after joining this program, you can refer to 让IDEA IDE识别Lombok的注解 to solve
Now, run the program and visit the address localhost:8080/todo, you can see that the Todo list is assembled into a json data format and returned.
1 | [{"id":1,"title":"Call Metting","desc":""},{"id":2,"title":"Print File","desc":""}] |
Next Step
In , we will add database functionality to the application.