swagger2笔记

105 阅读1分钟
  1. pom依赖
<!-- swagger2 配置  第三个是为了美化api文档界面的 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.6</version>
</dependency>
  1. 配置类
package com.imooc.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author Created by wcg
 * @Date 2019/11/7 21:39
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
    //http://localhost:8088/swagger-ui.html 原路径
    //http://localhost:8088/doc.html bootstarp路径
    //配置swagger2核心配置 docket,主要是添加要扫描controller的路径
    @Bean
    public Docket createResApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select().apis(RequestHandlerSelectors
                            .basePackage("com.imooc.controller"))
                .paths(PathSelectors.any())
                .build();

    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("天天吃货,电商平台接口api").
                contact(new Contact("imooc","https://www.imooc.com","abc@imooc.com"))
                        .description("专门为天天吃货提供的api文档")
                .version("1.0.1")
                .termsOfServiceUrl("https://www.imooc.com")
                .build();

    }
}

  1. 各注解类

@ApiIgnore/:用于controller类上,将配置中扫描的包下的该类忽略,这样文档页面不会展示此类下的接口/

@Api(value="注册登录",tags="注册登录的相关接口描述")/:用于controller类上,用于对接口类描述/

@ApiOperation(value = “用户名是否存在”,notes = “用户名是否存在”,httpMethod = “GET”) 主要放置在方法前边,用于展示对应接口的信息,以及请求方式;

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

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

  • @ApiParam:单个参数描述

  • @ApiModel:用对象来接收参数

  • @ApiProperty:用对象接收参数时,描述对象的一个字段

  • @ApiResponse:HTTP响应其中1个描述

  • @ApiResponses:HTTP响应整体描述

  • @ApiIgnore:使用该注解忽略这个API

  • @ApiError :发生错误返回的信息

  • @ApiImplicitParam:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值

  • @ApiImplicitParams:描述由多个 @ApiImplicitParam 注解的参数组成的请求参数列表