SpringBoot integrated Swagger (Swagger used), the generated interface document, the front and rear end of the separator to facilitate the development of

First on the outcome of a map.

 

 1, Maven relies

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <-! Swagger-ui for viewing ->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

2, requires a custom configuration class, and then added to the Spring container.

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;

//
@Configuration   //声明此类是配置类
@EnableSwagger2 // 支持Swagger
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xuecheng"))//扫描的路劲,代表com.xuecheng下面的类都可以被扫到
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swaggerapi文档")
                .description("Swaggerapi文档")
//                .termsOfServiceUrl("/")
                .version("1.0")
                .build();
    }
}

3、常用注解介绍

@Api 修饰整个类,描述Controller的作用,

@ApiOperation 描述一个类的方法,或者说一个接口

@ApiParam 单个参数描述

@ApiModel 用对象来接收参数

@ApiModelProperty 属性注释,用于对象属性上

@ApiResponse HTTP响应整体描述

@ApiError 发生错误的返回信息

@ApimplicitParam 一个请求参数

@ApimplicitParams 多个请求参数

4、接口书写

 

 因为参数中还有一个对象,所以再对象的属性上也可以加注解,描述。

 

5、启动项目,访问localhost:xx/wagger-ui.html,即可访问接口文档。文章开头有图。

6、Swagger接口生成工作原理。

(1)、系统启动,扫描到api工程中的Swagger2Configuration类

(2)、在此类中指定了包路径com.xuecheng,找到在此包下及子包下标记有@RestController注解的controller类

(3)、根据controller类中的Swagger注解生成接口文档。

7、接口测试

  打开接口文档页面,输入请求参数,点击“Try it out”发起请求。即可向项目发请求,用于测试。

  

Guess you like

Origin www.cnblogs.com/super-hu/p/12033445.html