Add Swagger to the SpringBoot project to automatically generate API documentation + (swagger-bootstrap-ui) documentation interface optimization + how to modify the document can’t be found

In the development of separation of front and back ends, the back end needs to provide API interface documentation for the front end, which is a very important step. However, the writing and updating of interface documents also takes a lot of time during the development process, especially the content of some parameters, it is easy for front-end personnel to fail to use the interface due to incorrect writing. Swagger was born to solve this problem. During the development process, API documents are automatically generated according to the parameters configured by the back-end developers. This article is about the basic functions of using this plug-in in the Springboot project.

One, Swagger is concerned about the solution

annotation Introduction
@Api @Api is used on a class to illustrate the role of the class. You can mark a Controller class as a Swagger document resource
@ApiParam Description of parameters used for methods in Controller
@@ApiOperation Used in the method in the Controller, explain the role of the method, the definition of each interface
@ApiImplicitParam and @ApiImplicitParams Used in the method, to explain the individual request parameters
@ApiModel Used for fields, indicating the description of model attributes
@ApiModelProperty Indicates the description of the class, which is used to describe the parameter reception in the entity class
@ApiResponse and @ApiResponses @ApiResponse is used in the method to explain some information of the interface response; @ApiResponses assembles multiple @ApiResponse

Here is a brief introduction. For details, see the specific use in the springboot project below.

Second, the actual application in the springboot project
(1) cited dependency

<!--Swagger依赖-->
	<dependency>
		<groupId>io.springfox</groupId>
		<artifactId>springfox-swagger2</artifactId>
		<version>2.9.2</version>
	</dependency>
	<!--Swagger UI依赖-->
	<dependency>
		<groupId>io.springfox</groupId>
		<artifactId>springfox-swagger-ui</artifactId>
		<version>2.9.2</version>
	</dependency>

The two dependencies introduced here, the first one is the swagger dependency. After introducing this dependency, you can view the returned json document, which is very cumbersome and complicated, and the readability is extremely poor. At this time, a display UI is needed. After the introduction It is a dependency of swagger to display the UI.
(2) Configure swagger

@Configuration
@EnableSwagger2
@ComponentScan(basePackages = {
    
     "com.example.api.controller" })
public class SwaggerConfig {
    
    
    @Bean
    public Docket buildDocket(){
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.api.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo buildApiInf(){
    
    
        return new ApiInfoBuilder()
                //页面标题
                .title("秒杀商城API文档")
                //描述
                .description("简单优雅的restful风格")
                //创建人信息
                .contact(new Contact("Curry-Kun","127.0.0.1:8080/","[email protected]"))
                .termsOfServiceUrl("")
                //版本号
                .version("1.0")
                .build();
    }
}

(Three) configuration interface class and entity class
1.controller layer

@RestController
@RequestMapping("/miaosha")
@Api(tags = "秒杀功能模块API")
public class MiaoshaAPIController {
    
    

    @Autowired
    ProductService productService;

    @ApiImplicitParams({
    
    
            @ApiImplicitParam(name = "pageNo",value = "页码数",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "展示条数",required = true,dataType = "int",paramType = "query")
    })

    /**
     * 商品列表页api
     * @request
     * pageNo
     * pageSize
     * @response
     * success
     * fail
     *
     * */
    @ApiOperation(value = "查询系统秒杀商品列表",notes = "采取分页的形式展示,需要pageNo页码数和pageSize每页展示条数")
    @PostMapping(value = "product_list_api")
    public ResponseResult product_list_api(@RequestParam(value = "pageNo",defaultValue = "1")int pageNo,
                                           @RequestParam(value = "pageSize",defaultValue = "6")int pageSize,
                                           User user){
    
    
        if(user == null){
    
    
            return ResponseResult.error(ResponseCode.NO_LOGIN);
        }
        PageInfo<ProductVo> page = productService.listProcuctVo(pageNo,pageSize);
        return ResponseResult.success(page);
    }

This involves the use of @Api, @ApiImplicitParams, @ApiImplicitParam, and @ApiOperation. From the above code, you can see their respective roles in more detail.
Thought that the returned results are all encapsulated in ResponseResult, so it also needs to be annotated

@Data
@ApiModel
public class ResponseResult<T> {
    
    
    @ApiModelProperty(value = "返回状态码")
    private int code;
    @ApiModelProperty(value = "返回信息")
    private String msg;
    @ApiModelProperty(value = "返回数据")
    private T data;
    /**
     * 不同的data数据类型对应不同的ResponseResult的类型
     * */

    /**
     *return code message data 方法构造器
     * */
    public ResponseResult(ResponseCode rc,T data) {
    
    
        this.data = data;
        this.msg = rc.msg;
        this.code = rc.id;
    }
    /**
     * return code message
     * */
    public ResponseResult(ResponseCode rc) {
    
    
        this.msg = rc.msg;
        this.code = rc.id;
    }
    /**
     * success
     * */
    public static <T> ResponseResult<T> success(T data){
    
    
        return new ResponseResult<T>(ResponseCode.SERVER_SUCCESS,data);
    }
    /**
     * error
     * */
    public static  <T> ResponseResult<T> error(ResponseCode rc){
    
    
        return new ResponseResult<T>(rc);
    }
}

This involves the use of @ApiModel and @ApiModelProperty annotations.
Start the project and visit http://{ip}:{port}/swagger-ui.html#/
Insert picture description here
(4) Optimize the UI The
above UI is still not very convenient in use. You can also make a more user-friendly page. swagger-bootstrap-ui
1. Introduce dependencies

<dependency>
		<groupId>com.github.xiaoymin</groupId>
		<artifactId>swagger-bootstrap-ui</artifactId>
		<version>1.6</version>
	</dependency>

At this time, you need to visit http://{ip}:{port}/doc.html
Insert picture description here
and support online debugging. As long as the annotations you write are detailed enough, novices can understand them.

3. What should I do if I cannot find the generated API documentation page?
1. The page cannot be accessed error: No mapping for GET /swagger-ui.html
This situation occurs because the system passes the requested swagger-ui.html as a parameter, which will definitely cause an error. At this time, you need to modify WebMvcConfigurer, intercept swagger-ui.html, and configure the file location.


@Configuration
public class WebConfig implements WebMvcConfigurer{
    
    

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        registry.addResourceHandler("doc.html")//swagger-ui.html
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }
}

2. A blank page
appears after the visit. In this case, you must confirm whether the UI dependency used by swagger is imported normally. It is likely that the dependency is not imported, causing the swagger-ui.html file to not be found. Go to dom.xml to track it. Or when viewing the system dependencies, if you confirm that there are no UI dependencies you need, you can downgrade the dependencies to use.

Guess you like

Origin blog.csdn.net/Wangdiankun/article/details/106506164