The original article was published on wechat official account: 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, and Actuator, etc. As an Android developer, the learning of Spring Boot will focus on how to use it. All articles will be based on corresponding cases. This article will introduce how to use Spring Boot to develop an interface from the following aspects:

  1. The Spring Boot project is initialized
  2. Create a Spring Boot project using IDEA
  3. Spring Boot project directory structure
  4. Describe POM files
  5. Implement a simple interface
  6. The interface test

The Spring Boot project is initialized

To create a Spring application, start with Spring Initializr. You can quickly select your project’s dependencies. You can visit https://start.spring.io/ to complete the creation of a Spring application, as shown below:

Through the configuration can generate the corresponding configuration information of the project source package, using IntelliJ IDEA or other IDE can be opened.

Create a Spring Boot project using IDEA

The most common way is definitely to use an IDE to create spring-related projects, and IntelliJ IDEA was chosen to create Spring Boot projects.

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

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

Step 3: Configure the project information based on the project, and then select Next:

Step 4: Select the Web->Spring Web and Spring Boot versions. This step essentially adds the dependencies that support Web development to the project, which you will see in the POM file, and then select Next:

Step 5: Select Finish to complete the project creation:

Spring Boot project directory structure

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

│ pom. XML └ ─ SRC ├ ─ the main │ ├ ─ Java │ │ └ ─ com │ │ └ ─ manu │ │ └ ─ hello │ │ SpringBootHelloWorldApplication. Java │ │ │ ├─ ├─ ├─ ├─ ├─ │ ├─static│ └ ─ templates └ ─ test └ ─ Java └ ─ com └ ─ manu └ ─ hello SpringBootHelloWorldApplicationTests. JavaCopy the code

The main directories and files are described as follows:

  • Pom.xml: The project is based on a Mavan dependency configuration file. If the project is based on Gradle, there is a gradle file.
  • SRC /main/ Java: project source directory;
  • SRC /main/resources: resources file directory;
  • SRC /test: indicates the test file directory.
  • Application. properties: configuration file, or yML file;
  • Static: Directory of static resource files, such as HTML, CSS, and JS.
  • Templates: directory for template files, such as Thymeleaf.
  • SpringBootHelloWorldApplication: class of project startup.

Describe POM files

POM is short for Project Object Model. Maven Project uses XML to configure projects. The pop. XML file is similar to the build.gradle file in Android development. Spring Boot projects can also be built using Gradle. Take a look at the poM file contents of the Spring Web project:


      
<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>
    <! -- Inherited 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 - the SNAPSHOT</version>
    <! -- Type of artifact generated by the project, default JAR, others such as 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>

    <! - rely on -- -- >
    <dependencies>
        <! - support 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>

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

Other specific configurations of POM files are not covered here.

Implement a simple interface

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

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

Where @SpringBootApplication is equivalent to @EnableAutoConfiguration, @ComponentScan and @Configuration together, mainly used to configure the startup class, here will implement an interface on this basis, First create a MessageBean as the returned 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;
    }
    // ...
}
Copy the code

Then, create the corresponding controller class, where the @RestController annotation marks the HelloWorldController class as a controller, and the returns from the methods in this class will be converted to objects instead of page views. This is equivalent to the annotation @controller and @responseBody.

The returned MessageBean will be converted to JSON, which is automatically supported by Spring’s HTTP message converter. Finally using MappingJackson2HttpMessageConverter MessageBean object is converted to 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 newMessageBean(counter.incrementAndGet(), author, message); }}Copy the code

@restController is equivalent to what @Controller and @responseBody use together, which is to convert the object returned in Controller to the corresponding format.

@controller is responsible for class injection, so I won’t go into that, but if you’ve used the Dagger framework of Android development you can understand the use of the @Controller annotation, and the @responseBody annotation is basically to convert the returned object to a specific format, The default is JSON.

@requestMapping is used for address mapping in a class or method. If it is used in a class, all methods in the class must use this path as the parent path of the request. If it is used in a method, it represents the path of the current response. You can also use @getmapping. @getmapping actually specifies the RequestMethod as requestmethod. GET by default, and @requestparam is used to configure the request parameters.

The interface test

Run SpringBootHelloWorldApplication, run successful screenshots are as follows:

Access the following interface to view the returned data:

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

The following data is returned:

{"id":3."author":"jzman"."message":"Hello"}
Copy the code

At this point, you have implemented a simple interface using Spring Boot that is configured in a similar way to Retryfit in Android development, and is easily configured using annotations.