Development of an interface in the Spring Boot series

The original text was first published on WeChat public account: Jongxingzhi (jzman-blog)

Spring Boot is used to simplify the development of Spring applications and reduce unnecessary configuration processes. Its main features include Spring Boot Starter, automatic configuration, command line interface, Actuator, etc. As an Android developer, the learning of Spring Boot will be based on Will use the main, all articles will be based on the corresponding case, this article will introduce how to use Spring Boot to develop an interface from the following aspects:

  1. Spring Boot project initialization
  2. Use IDEA to create a Spring Boot project
  3. Spring Boot project directory structure
  4. Brief description of POM file
  5. Implement a simple interface
  6. Interface test

Spring Boot project initialization

Spring applications are created from the beginning of Spring Initializr, you can quickly select the project dependencies can be accessed https://start.spring.io/to complete the creation of Spring applications, as shown below:

0

The project source code package corresponding to the configuration information can be generated through configuration, and it can be opened with IntelliJ IDEA or other IDE.

Use IDEA to create a Spring Boot project

The most common way is definitely to use IDE to create Spring related projects, here choose IntelliJ IDEA to create Spring Boot project.

Step 1 : Select File->New->Project, as follows:

1

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

2

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

3

Step 4 : Select the version of Web->Spring Web and Spring Boot. This step is actually to add dependencies that support Web development to the project, and then you will see the relevant dependencies in the pom file, and then select Next:

4

Step 5 : Select Finish to complete the creation of the project:

Spring Boot project directory structure

The main directory structure of the 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 project is based on the dependency configuration file of mavan. If the project is based on gradle, there is a corresponding gradle file;
  • src/main/java: project source code directory;
  • src/main/resources: resource file directory;
  • src/test: test file directory;
  • application.properties: configuration file, you can also use yml file for configuration;
  • static: static resource file directory, such as html, css, js, etc.;
  • templates: template file directory, such as Thymeleaf, etc.;
  • SpringBootHelloWorldApplication: Project startup class.

Brief description of POM file

POM is the abbreviation of Project Object Model. The maven project uses xml to configure the project. The pom.xml is used to configure the maven project. 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, which is mainly used to manage project dependencies, configure project information, etc. Take a look at the content of the pom file of the 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模型版本 -->
    <modelVersion>4.0.0</modelVersion>
    <!--继承的父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <!--项目信息-->
    <groupId>com.manu</groupId>
    <artifactId>spring-boot-hello-world</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!--项目产生的构件类型,默认jar,其他如war、rar、ejb、ear、par等-->
    <packaging>jar</packaging>
    <name>spring-boot-hello-world</name>
    <description>Spring Boot sample for Hello World!</description>

    <!--属性设置-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!--依赖-->
    <dependencies>
        <!--支持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>
        <!--插件-->
        <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, I will not go into details here.

Implement a simple interface

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

@EnableAutoConfiguration
@ComponentScan
@Configuration
//@SpringBootApplication
public class SpringBootHelloWorldApplication {
    
    
    public static void main(String[] args) {
    
    
        // 启动程序,包括Spring容器、内嵌的Tomcat等
        SpringApplication.run(SpringBootHelloWorldApplication.class, args);
    }
}

Which @SpringBootApplicationis equivalent to @EnableAutoConfiguration, @ComponentScanand @Configurationused with, mainly used to configure the startup class, there will implement an interface based on this, first create a MessageBeanas a return entity class, 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, the controller creates a corresponding class in which annotation @RestControllerthe class HelloWorldControllermark a controller, the method returns inside the class will be converted into an object instead of a page view, equivalent to the annotations @Controllerand @ResponseBodyused together.

The return MessageBeanwill be converted json, the process is automatically supported by the HTTP message Spring converter, the end use MappingJackson2HttpMessageConverterto MessageBeanconvert an object to the corresponding jsonformat

/**
 * @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);
    }
}

@RestControllerEquivalent @Controllerand @ResponseBodythe effect of use with an object is to convert Controller returned to the corresponding format.

@ControllerInjecting operation is responsible for the class, there is not an in-depth, if used Dagger Android development framework can be helpful in understanding the notes @Controllerused @ResponseBodyprimarily to convert the returned object identifier for a specific format, the default format is json.

@RequestMappingFor address mapping, it can be used on classes and methods. If used on a class, all methods in the class that respond to requests must use this as the parent path. If used on a method, it means the path of the current response, as shown in the code above. can be implemented using a GET request @RequestMapping, it may also be used @GetMapping, @GetMappingin fact, specify a default request method RequestMethod.GET, in addition @RequestParamto the parameter configuration request.

Interface test

Run SpringBootHelloWorldApplication, the screenshot of a successful run is as follows:

SpringBootHelloWorldApplication

Visit 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"}

So far, a simple interface has been implemented using Spring Boot. The interface configuration method is similar to Retryfit in Android development, and the relevant configuration can be easily completed using annotations.

Insert picture description here

Guess you like

Origin blog.csdn.net/jzman/article/details/109040806