Spring Boot + Swagger2 automatically generates api interface documentation

1. What is Swagger

        Due to the rapid development and convenient deployment of Spring Boot, it is believed that a large part of Spring Boot users will use it to build RESTful APIs. Due to the multi-terminal situation (mobile terminal, web front end, applet, etc.), we will abstract the RESTful API and share some underlying business codes. 

       Due to the numerous interfaces and complex details, some api frameworks have been spawned. Swagger stands out by virtue of its simple use and real-time updates. Swagger can be easily integrated into Spring Boot, and cooperate with the Spring MVC program to organize a powerful RESTful API document. It can not only reduce the workload for us to create documents, but also integrate the description content into the implementation code, so that the maintenance document and the modified code are integrated, which allows us to modify the document description while modifying the code logic. In addition, Swagger2 also provides a powerful page testing function to debug each RESTful API.

With SwaggerHub, you can:

Two, use Swagger in SpringBoot

2.1 Add swagger dependency in pom

To use swagge, we first need to add swagger dependency to the project's pom (maven build is used here, if it is gradle, please add it in build.gradle). There are two main dependencies we need to add, namely swagger and swagger-ui. If you want to use other functions (such as interface document export), you also need to introduce the corresponding package.

<!--swagger API获取-->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<!--swagger-ui API获取-->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

2.2 Add swagger configuration class

Create SwaggerConfig.java class

package com.oycbest.springbootswagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Description: swagger 配置类
 * @Author oyc
 * @Date 2020/5/5 3:47 下午
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi() {
        // 指定扫描包路径
        return new Docket(DocumentationType.SWAGGER_2) // 指定生成的文档的类型是Swagger2
//                .pathMapping("/swagger")
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo(apiInfo()) // 配置文档页面的基本信息内容
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .apis(RequestHandlerSelectors.basePackage("com.oycbest.springbootswagger.controller"))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("描述:Spring Boot中使用Swagger2构建RESTful APIs")
                // 描述
                .description("swagger 测试demo")
                // 作者信息
                .contact("oyc")
                .termsOfServiceUrl("http://www.oycyqr.xyz")
                // 版本
                .version("版本号:" + "1.0.1")
                .build();
    }
}
  • @Configuration configuration class, which is loaded at startup
  • @EnabledSwagger2 identifies the project to start the SwaggerApi document
  • Some basic information displayed on the Swagger page of the ApiInfo class
  • RequestHandlerSelectors.basePackage("com.oycbest.springbootswagger.controller") where com.oycbest.springbootswagger.controller is the path to scan the package

2.3 Add swagger interface annotations in the controller

package com.oycbest.springbootswagger.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: 测试swagger controller
 * @Author oyc
 * @Date 2020/5/5 3:43 下午
 */
@RestController
@Api(tags = "SwaggerController", description = "SwaggerController | 测试swagger")
@RequestMapping("api")
public class SwaggerController {


    @GetMapping("hello")
    @ApiOperation(value="hello 方法", notes="hello Swagger测试方法--hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("test1")
    @ApiOperation(value="test1 方法", notes="hello Swagger测试方法--test1")
    public String test1(){
        return "test1";
    }

    @GetMapping("test2")
    @ApiOperation(value="test2 方法", notes="hello Swagger测试方法-test2")
    public String test2(){
        return "test2";
    }
}
  • @Api decorates the entire class and describes the role of Controller.
  • @ApiOperation modifies a method of a class, or an interface, to describe the function and precautions of this method. If not used, use the function name as the method function.

       Parameters: value="Describe the purpose and function of the method"

                notes="Remarks on the method"

  • @apiResponses: used in the request method to represent a set of responses
  • @ApiResponse: Used in @ApiResponses, generally used to express an incorrect response message

        code: number, such as 400
        message: information, such as "request parameters are not filled in"
        response: the class that throws the exception

  • @ApiImplicitParams modifies the method to describe the role of the parameters of this method. If not used, use the parameter name as the function of the parameter.
  • @ApiImplicitParam: Used in the @ApiImplicitParams annotation to specify all aspects of a request parameter
            name: parameter name
            value: Chinese character description and explanation of the
            parameter required: whether the parameter must be passed
            paramType: where the parameter is placed
                · header --> of the request parameter Get: @RequestHeader
                · query --> Get request parameters: @RequestParam
                · path (for restful interface) --> Get request parameters: @PathVariable
                · body (not commonly used)
                · form (not commonly used)    
            dataType: parameter type , Default String, other values ​​dataType="Integer"       
            defaultValue: the default value of the parameter
  • @ApiModel modifies the entity class and can describe the function of this class.
  • @ApiModelProperty modifies the properties of the entity class and can describe the role of this property.
  • @ApiIgnore modifies parameters, methods, and classes, and can ignore modified objects when automatically generating documents.
  • @ApiError: Information returned when an error occurs 

2.4 View & test interface

If you do not introduce a security framework or set a path interception mechanism, you can directly visit http://127.0.0.1:8080/[project name]/swagger-ui.html to view the interface.

Interface list:

Test interface:

Source address: https://github.com/oycyqr/springboot-learning-demo/tree/master/springboot-swagger

 

Guess you like

Origin blog.csdn.net/u014553029/article/details/105935558