# Swagger2简单使用教程

1、简介

​ Swagger是为了解决企业中接口(api)中定义统一标准规范的文档生成工具。很多采用前后端分离的模式,前端只负责调用接口,进行渲染,前端和后端的唯一联系,变成了API接口。因此,API文档变得越来越重要。swagger是一个方便我们更好的编写API文档的框架,而且swagger可以模拟http请求调用。

2、常用注解与示例

  • @Api()用于类:表示标识这个类是swagger的资源

  •  @Api("用于类")
      @Controller
      public class swaggerTest(){
      }
    
  • @ApiOperation()用于方法:表示一个http请求的操作

  • @Api("ApiOperation测试")
    @Controller
    public class swaggerTest(){
        @ApiOperation(value = "apiOperationTest", notes = "apiOperation测试")
        public void apiOperationSwaggerTest(){
        }
    }
    
  • @ApiParam():用于方法,参数,字段说明:表示对参数的添加元数据(说明或是否必填等)

  • @Api("ApiParam测试")
    @Controller
    public class swaggerTest(){
        @ApiOperation(value = "apiOperationTest", notes = "apiOperation测试")
        public void apiOperationTest(@ApiParam(name = "id", value = "1", required = true) Integer id){
        }
    }
    
  • @ApiModel()用于类:表示对类进行说明,用于参数用实体类接收

  • @ApiModel(description = "实体类", value = "实体类")
    public class City implements Serializable {
    
    }
    
  • @ApiModelProperty()用于方法,字段:表示对model属性的说明或者是数据操作更改

  • @ApiModel(description = "实体类", value = "实体类")
    public class City implements Serializable {
        @ApiModelProperty(name = "id", value = "编号", required = false, exmaple = "1")
        private int id;
    }
    
  • @ApiIgnore()用于类,方法,方法参数:表示这个方法或者类被忽略

  • @ApiIgnore
    @Api(tags = {"Xxx控制类"})
    @RestController
    @RequestMapping("/xxx")
    public class XxxController {
    
    }
    
  • @ApiImplicitParam()用于方法:表示单独的请求参数

    @ApiImplicitParams()用于方法,包含多个@ApiImplicitParam

  • @Api("测试1")
      @Controller
      public class swaggerTest(){
          @ApiOperation(value = "apiOperationTest", notes = "apiOperation测试")
          @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer", paramType = "query"),
                            @ApiImplicitParam(name = "name", value = "name", required = true, dataType = "String", paramType = "query")
        })
          public void apiOperationSwaggerTest(Integer id, String name){
          }
      }
    

3、使用步骤

maven导入依赖

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

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>

创建配置类

给出一些基础配置

@Configuration
@EnableSwagger2 //开启Swagger2
public class Swagger2 {

    //是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
    @Value(value = "${swagger.enabled}")
    Boolean swaggerEnabled;
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxxxxx.xxxxx")) //你的项目基础包名
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("标题")
                .description("api接口文档")
                .version("1.0") //版本
                .build();
    }

}

SpringBoot 配置文件 开启swagger

  • application-dev.yml文件
swagger:
    enabled: true

注意导包不要导错

import org.springframework.beans.factory.annotation.Value;
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;

实体类demo

@Entity
@Table(name = "city")
public class City implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    @Getter
    @Setter
    private int ID;
    @Column(name = "Name")
    @ApiModelProperty(value = "城市名字", dataType = "String", name = "name", example = "Kabul")
    @Getter
    @Setter
    private String Name;

代码中的@Getter@Setter 注解是使用 lombok代替get与set方法,使用方法参考另一篇

service与dao略过 看controller的写法

 @ApiOperation(value="按id查询城市信息")
    @ResponseBody
    @GetMapping("/queryCityList")
    public String queryCityList(@RequestParam("id") int id)  {
        List<City> queryCityList = cityService.queryCityList(id);
        String jsonString = JSON.toJSONString(queryCityList);
        return  jsonString;
    }

4、浏览器中使用