Swagger介绍与使用

情到浓时终转凉″ 提交于 2020-01-28 01:50:24

什么是swgaaer

swagger是一个功能简单但强大的API工具,可以非常友好的对外展示接口,以及接口文档的生成

与Spring Boot集成

maven配置依赖

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.5.0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.5.0</version>
</dependency>

编写swagger配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 选择那些路径和api会生成document
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //swagget扫描目录
                //.apis(RequestHandlerSelectors.basePackage("com.itcast.controller"))
                // 对所有路径进行监控
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot中使用Swagger2构建RESTful APIs")
                .description("API 描述")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}

访问地址

http://${host}:${port}/swagger-ui.html

swagger访问界面

常用注解

Api 用于类,表示这个类是swagger资源

  • value 类说明
  • tags 类分组,同一个tags下的类会分在同一组

ApiOperation 用于方法

  • value 方法描述
  • notes 提示内容

ApiParam 用于参数,方法,字段说明

  • name 参数名
  • value 参数说明
  • required 是否必填

ApiModel 用于实体类

  • value 实体类名
  • description 描述

ApiModelProperty 字段

  • value 字段说明
  • name 重写属性名称
  • dataType 重写属性类型
  • required 是否必填
  • example 举例说明
  • hidden 隐藏

ApiImplicitParams 用于方法,可以包含多个@ApiImplicitParam

  • name 参数名称
  • value 参数说明
  • dataType 数据类型
  • paramType 参数类型
  • example 举例说明

生成接口文档

修改maven依赖

生成接口文档只需要将springfox-swagger-ui包改为引用swagger-bootstrap-ui包即可

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.5.0</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>

访问地址

http://${host}:${port}/doc.html

swagger-bootstrap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!