banner
jzman

jzman

Coding、思考、自觉。
github

Developing an API in the Spring Boot Series

PS: It's never too late to decide to start.

Spring Boot is used to simplify the development of Spring applications, reducing unnecessary configuration processes. Its main features include Spring Boot Starter, auto-configuration, command-line interface, Actuator, etc. As an Android developer, the learning of Spring Boot will focus on practical usage, with all articles based on corresponding cases. This article will introduce how to use Spring Boot to develop an interface from the following aspects:

  1. Spring Boot project initialization
  2. Creating a Spring Boot project using IDEA
  3. Spring Boot project directory structure
  4. Brief introduction to the POM file
  5. Implementing a simple interface
  6. Interface testing

Spring Boot Project Initialization#

Creating a Spring application starts with Spring Initializr, which allows for quick selection of project dependencies. You can visit https://start.spring.io/ to complete the creation of a Spring application, as shown in the figure below:

0

By configuring, you can generate the corresponding configuration information project source package, which can be opened using IntelliJ IDEA or other IDEs.

Creating a Spring Boot Project Using IDEA#

The most common way is to use an IDE to create Spring-related projects. Here, we choose IntelliJ IDEA to create a Spring Boot project.

Step 1: Select File->New->Project, as shown below:

image

Step 2: Select Spring Initializr, with Project SDK at least JDK 1.8, then select Next:

image

Step 3: Configure project information according to the project settings, then select Next:

image

Step 4: Select Web->Spring Web and the version of Spring Boot. This step actually adds dependencies for web development to the project, which will be seen in the pom file later. Then select Next:

image

Step 5: Select Finish to complete the project creation:

image

Spring Boot Project Directory Structure#

The main directory structure of a Spring Boot project is as follows:

│ pom.xml
└─src
    ├─main
    │  ├─java
    │  │  └─com
    │  │      └─manu
    │  │          └─hello
    │  │                  SpringBootHelloWorldApplication.java
    │  │
    │  └─resources
    │      │ application.properties
    │      │
    │      ├─static
    │      └─templates
    └─test
        └─java
            └─com
                └─manu
                    └─hello
                            SpringBootHelloWorldApplicationTests.java

The main directories and files are introduced as follows:

  • pom.xml: The dependency configuration file based on Maven for the project. If the project is based on Gradle, there will be a corresponding Gradle file.
  • src/main/java: The source code directory of the project.
  • src/main/resources: The resource file directory.
  • src/test: The test file directory.
  • application.properties: The configuration file, which can also be configured using a yml file.
  • static: The static resource file directory, such as html, css, js, etc.
  • templates: The template file directory, such as Thymeleaf, etc.
  • SpringBootHelloWorldApplication: The project startup class.

Brief Introduction to the POM File#

POM stands for Project Object Model. Maven projects are configured through XML, and pom.xml is used to configure Maven projects. The pom.xml file is similar to the build.gradle file in Android development. Of course, Spring Boot projects can also be built using Gradle, mainly used to manage project dependencies, configure project information, etc. Let's take a look at the contents of the pom file for a Spring Web project:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!--pom model version -->
    <modelVersion>4.0.0</modelVersion>
    <!--parent project-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <!--project information-->
    <groupId>com.manu</groupId>
    <artifactId>spring-boot-hello-world</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!--project artifact type, default is jar, others include war, rar, ejb, ear, par, etc.-->
    <packaging>jar</packaging>
    <name>spring-boot-hello-world</name>
    <description>Spring Boot sample for Hello World!</description>

    <!--property settings-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!--dependencies-->
    <dependencies>
        <!--support for Web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!--build-->
    <build>
        <!--plugins-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

As for other specific configurations of the pom file, we will not go into detail here.

Implementing a Simple Interface#

According to the steps above, the project has been created. The project startup class is as follows:

@EnableAutoConfiguration
@ComponentScan
@Configuration
//@SpringBootApplication
public class SpringBootHelloWorldApplication {
    public static void main(String[] args) {
        // Start the application, including the Spring container, embedded Tomcat, etc.
        SpringApplication.run(SpringBootHelloWorldApplication.class, args);
    }
}

The @SpringBootApplication annotation is equivalent to using @EnableAutoConfiguration, @ComponentScan, and @Configuration together, mainly used to configure the startup class. Here, we will implement an interface based on this. First, create a MessageBean as the entity class to be returned, as follows:

/**
 * @Desc: MessageBean
 * @Author: jzman
 * @Date: 2020/3/6 15:51.
 */
public class MessageBean {
    private long id;
    private String author;
    private String message;

    public MessageBean(long id, String author, String info) {
        this.id = id;
        this.author = author;
        this.message = info;
    }
    // ...
}

Then, create the corresponding controller class, where the @RestController annotation marks the class HelloWorldController as a controller. The methods in this class will return objects instead of page views, equivalent to using @Controller and @ResponseBody together.

The returned MessageBean will be converted to json, a process automatically supported by Spring's HTTP message converters. Finally, MappingJackson2HttpMessageConverter will convert the MessageBean object into the corresponding json format.

/**
 * @Desc: HelloWorldController
 * @Author: jzman
 */
//@Controller
//@ResponseBody
@RestController
public class HelloWorldController {

    private final AtomicLong counter = new AtomicLong();

//    @RequestMapping(value = "/message", method = RequestMethod.GET)
    @GetMapping("/message")
    public MessageBean message(@RequestParam(name = "author", defaultValue = "jzman") String author,
                               @RequestParam(name = "message", defaultValue = "Hello world!") String message) {
        return new MessageBean(counter.incrementAndGet(), author, message);
    }
}

@RestController is equivalent to the effect of using @Controller and @ResponseBody together, which converts the objects returned from the Controller into the corresponding format.

@Controller is responsible for class injection operations, which will not be explored in depth here. If you have used the Dagger framework in Android development, it may help to understand the use of the @Controller annotation. @ResponseBody mainly indicates that the returned object should be converted to a specific format, with the default being json format.

@RequestMapping is used for address mapping and can be used at both the class and method levels. If used at the class level, all methods in that class responding to requests will have this as the parent path. If used at the method level, it indicates the current response path. In the code above, a GET request can be implemented using @RequestMapping, or @GetMapping. The @GetMapping actually defaults to specifying the request method as RequestMethod.GET. Additionally, @RequestParam is used to configure request parameters.

Interface Testing#

Run SpringBootHelloWorldApplication, and the successful run screenshot is as follows:

image

Access the following interface to view the returned data:

http://localhost:8080/message?author=jzman&message=Hello

The returned data is as follows:

{"id":3,"author":"jzman","message":"Hello"}

Thus, a simple interface has been implemented using Spring Boot, and the interface configuration method is similar to Retrofit in Android development, easily completing the relevant configuration using annotations.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.