Spring Boot Tutorial - swagger-ui

1. What is Swagger?

Swagger`The goal is to define a standard language-independent interface for REST APIs that enables people and computers to discover and understand the capabilities of various services without seeing the source code or documents or through network traffic detection.When services are defined by Swagger, consumers can interact with remote services through a small amount of implementation logic.Similar to low-level programming interfaces, Swagger takes away many guesses when calling services. browse Swagger To learn more about the Swagger project, including additional libraries that support other languages.

2. Integrate Swagger into your project

  • 2.1 Introducing maven dependency

    I used swagger2 in my own project.

    <!--springboot Parent Project-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <dependencies>
            <!--springboot frame web assembly-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
            <!--swagger-ui assembly-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>
            <!--swagger assembly-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <!--mybatis integration springboot assembly-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>
            <!--mysql Database Connection Driver-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>
            <!--lombok assembly-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.10</version>
            </dependency>
        </dependencies>
    
        <build>
            <!--springboot Of maven Plug-in unit-->
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <compilerArgs>
                            <arg>-parameters</arg>
                        </compilerArgs>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
  • 2.2 Configuration of Swagger

    SwggerConfig.java:

    package com.butterflytri.config;
    
    import com.google.common.base.Predicates;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.service.Parameter;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    /**
     * @author: WJF
     * @date: 2020/5/21
     * @description: SwaggerConfig
     */
    
    /**
     * {@link Configuration}: Flag This is a configuration class that will be automatically loaded when the spring boot boot boot boot class starts.
     * {@link Profile}: Explain loading profile'application.yml'load the corresponding configuration.
     * {@link EnableSwagger2}: Enable configuration of Swagger2.
     */
    @Configuration
    @Profile("dev")
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Bean
        public Docket restApi() {
            Class[] classes = this.getClasses();
            Set<String> consumesSet = new HashSet<>();
            consumesSet.add("application/x-www-form-urlencoded");
            return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .globalOperationParameters(parameters())
                .ignoredParameterTypes(classes)
                .forCodeGeneration(true)
                .consumes(consumesSet)
                .select()
                .apis(Predicates.and(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)))
                .paths(PathSelectors.any())
                .build();
        }
    
        /**
         * API Basic information about the document
         * @return ApiInfo
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Student Management Platform")
                    .description("Student Management Platform Document")
                    .termsOfServiceUrl("http://127.0.0.1:8080/butterflytri/swagger-ui.html")
                    .contact(new Contact("wjf", "http://butterflytri.com", "butterflytri@163.com"))
                    .version("2.0")
                    .build();
        }
    
        /**
         * Swagger2 You can add parameters to the Swagger2 document
         * @return List<Parameter>
         */
        private List<Parameter> parameters() {
            // Add a parameter butterflytri, parameter description: Undead Butterfly
            ParameterBuilder paramBuilder = new ParameterBuilder();
            List<Parameter> paramList = new ArrayList<Parameter>();
            paramBuilder.name("butterflytri")
                    .description("Undead Butterfly")
                    .modelRef(new ModelRef("string"))
                    .parameterType("header")
                    .required(true)
                    .build();
            paramList.add(paramBuilder.build());
            return paramList;
        }
    
    
        /**
         * Get the class array
         * @return Class[]
         */
        private Class[] getClasses() {
            return new Class[]{};
        }
    
    }
    
    
  • 2.3 Control Layer

    StudentController.java:

    package com.butterflytri.controller;
    
    import com.butterflytri.entity.Student;
    import com.butterflytri.service.StudentService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    /**
     * @author: WJF
     * @date: 2020/5/16
     * @description: StudentController
     */
    @Api(tags = "Student Management Interface")
    @RestController
    @RequestMapping("/student")
    public class StudentController {
    
        @Resource
        private StudentService studentService;
    
        /**
         * GET : Request specific resources from the server.Example: GET/student (Get All Students)
         * @return List<Student>
         */
        @ApiOperation(value = "Query all students", httpMethod = "GET", notes = "Query all students")
        @GetMapping("/student")
        public List<Student> student() {
            return studentService.findAll();
        }
    
        /**
         * GET : Request specific resources from the server.For example: GET/student/1 (get id 1 student)
         * @param id
         * @return Student
         */
        @ApiOperation(value = "Query Student Details", httpMethod = "GET", notes = "Query Student Details")
        @ApiImplicitParam(name = "id", value = "Student id", required = true, paramType = "form", dataTypeClass = Long.class)
        @GetMapping("/student/{id}")
        public Student student(@PathVariable("id") Long id) {
            return studentService.findOne(id);
        }
    
        /**
         * POST : Create a new resource on the server.Example: POST/student
         * @param student
         */
        @PostMapping("/student")
        @ApiOperation(value = "Add Students", httpMethod = "POST", notes = "Add Students")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "studentName", value = "Student Name", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "studentNo", value = "Sno", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "sex", value = "Student Gender", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "age", value = "Student Age", required = true, paramType = "form", dataTypeClass = Integer.class)
        })
        public void student(@RequestBody Student student) {
            studentService.add(student);
        }
    
        /**
         * PUT : Update the resources on the server (the client provides the entire updated resource).Example: PUT/student/1 (Update all information for student number 1)
         * @param id
         */
        @PutMapping("/student/{id}")
        @ApiOperation(value = "according to id Modify Student Information(Large-scale)", httpMethod = "PUT", notes = "according to id Modify Student Information")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "id", value = "Student id", required = true, paramType = "from", dataTypeClass = Long.class),
                @ApiImplicitParam(name = "studentName", value = "Student Name", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "studentNo", value = "Sno", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "sex", value = "Student Gender", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "age", value = "Student Age", required = true, paramType = "form", dataTypeClass = Integer.class)
        })
        public void updateById(@PathVariable("id") Long id, Student student) {
            studentService.updateAll(id,student);
        }
    
        /**
         * DELETE : Delete a specific resource from the server.Example: DELETE/student/1 (delete student number 1)
         * @param id
         */
        @DeleteMapping("/student/{id}")
        @ApiOperation(value = "according to id Delete Student Information", httpMethod = "DELETE", notes = "according to id Delete Student Information")
        @ApiImplicitParam(name = "id", value = "Student id", required = true, paramType = "from", dataTypeClass = Long.class)
        public void deleteById(@PathVariable("id") Long id) {
            studentService.delete(id);
        }
    
        /**
         * PATCH : Update the resources on the server (the client provides the changed attributes, which can be seen as partial updates) and use them less, without an example.
         * @param id
         * @param student
         */
        @PatchMapping("/student/{id}")
        @ApiOperation(value = "according to id Modify Student Information(Small Range)", httpMethod = "PATCH", notes = "according to id Modify Student Information")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "id", value = "Student id", required = true, paramType = "from", dataTypeClass = Long.class),
                @ApiImplicitParam(name = "studentName", value = "Student Name", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "studentNo", value = "Sno", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "sex", value = "Student Gender", required = true, paramType = "form", dataTypeClass = String.class),
                @ApiImplicitParam(name = "age", value = "Student Age", required = true, paramType = "form", dataTypeClass = Integer.class)
        })
        public void updatePart(@PathVariable("id") Long id, Student student) {
            studentService.updatePart(id,student);
        }
    
    }
    
    

    These notes are also easy to understand, and I'm sure you'll be using them soon.The exact function of these notes is easy to understand without even having to look up the data. Explain here the @ApiImplicitParam property paramType, which has several values:

    • Header: Places in the request header for obtaining the request header parameters.Use @RequestHeader to receive parameters in your code.
    • query: Parameter splicing for get requests.Use @RequestParam to receive parameters in your code.
    • path: used to obtain restful interface request parameters.Use @PathVariable to receive parameters on the mapped address.
    • Body: Place in the body of the request and use @RequestBody to receive parameters.
    • Form: Pass parameters in the form form form.
  • 2.4 Entity

    Student.java:

    package com.butterflytri.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    
    import java.io.Serializable;
    
    /**
     * @author: WJF
     * @date: 2020/5/16
     * @description: Student
     */
    
    @ToString
    @Getter
    @Setter
    @ApiModel("Student Entity")
    public class Student implements Serializable {
    
        @ApiModelProperty("Student id")
        private Long id;
    
        @ApiModelProperty("Student Name")
        private String studentName;
    
        @ApiModelProperty("Sno")
        private String studentNo;
    
        @ApiModelProperty("Gender")
        private String sex;
    
        @ApiModelProperty("Age")
        private Integer age;
    
    }
    
    

    You can use the @ApiModelProperty annotation to identify the meaning of each Entity property.

  • 2.5 Run Results

    Start the project, accessHttp://127.0.0.1: 8080/butterflytri/swagger-Ui.htmlYou can see the following pages:

    Click on the student management interface to see StudentController.java All interface methods written in:

Click Models below to see what's in Entity Student.java Entity class:

Then open the query method for all students, call this method, and test the method by clicking Try it out:

Here I see a parameter butterflytri, which is also a required parameter because I am in SwaggerConfig.java This configuration file class is configured, and it's unclear to flip over and look at that configuration class.

After clicking the Try it out button, you can assign any value to this parameter. It has nothing to do anyway, just to show you a demonstration.Then click the execute button to see the results:

3. Project Address

This project portal:

This tutorial will be updated all the time. If you think the blogger can write it, pay attention to it, or it will be easier to learn it next time.

Tags: Programming Java Spring Maven Lombok

Posted on Tue, 02 Jun 2020 13:17:27 -0400 by .Stealth