SpringBoot整合Swagger2

目录

1.Swagger简介

2.Swagger2的maven依赖

3.Swagger配置类

4.配置Controller中的API


 

1.Swagger简介

 
Swagger是一款Restful接口的文档在线自动生成+功能测试的软件。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

官网:http://swagger.io/ 

GitHub地址:https://github.com/swagger-api/swagger-ui

2.Swagger2的maven依赖

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

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

3.Swagger配置类

通过@Configuration注解,让Spring-boot来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2Configuration。

apiInfo用来创建该Api的基本信息(这些基本信息会展现在文档页面中)

select() 函数返回一个 ApiSelectorBuilder 实例用来控制哪些接口暴露给Swagger2来展现。

一般采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。

该配置类与springboot的启动类放在同级目录:

SpringBoot整合Swagger2

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 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;

/**
 * @author dyt
 * @ClassName org.spring.springboot
 * @Description
 * @date 2019-03-10 22:12:31
 */
//通过@Configuration注解,让Spring-boot来加载该类配置。再通过@EnableSwagger2注解来启用
@Configuration
@EnableSwagger2
public class Swagger2 {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
//				当前包路径
				.apis(RequestHandlerSelectors.basePackage("org.spring.springboot.controller"))
				.paths(PathSelectors.any())
				.build();
	}
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				//页面标题
				.title("springboot利用swagger构建api文档测试项目")
                //描述
				.description("本工程的总体建设目标是通过实现站务系统功能改造和完善,规范客运站和运输公司等客运企业经营管理行为,提高其运行效率,提升公众出行服务效能。")
				.termsOfServiceUrl("https://blog.csdn.net/qq_20957669")
				//版本号
				.version("1.0")
				.build();
	}
}

4.配置Controller中的API

下面的内容是基于spring-boot进行配置的,使用Swagger2进行测试的类我们选择在controller层:


import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;



@Api("城市信息查询接口类")
@ApiResponses({  @ApiResponse(code=400,message = "请求参数没有填好"),
				    @ApiResponse(code=401,message = "401 - 未经授权:访问由于凭据无效被拒绝"),
				    @ApiResponse(code=403,message = "禁止访问"),
				    @ApiResponse(code=404,message="请求路径没有找到")
})
@RestController
public class CityRestController {

    @Autowired
    private CityService cityService;


    @ApiOperation(value = "根据id查询城市的信息",notes = "查询数据库中某个城市的信息,包含id,名称以及具体描述")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "城市id",dataType = "Long",paramType = "path",example = "1112")
    })
    @GetMapping(value = "/api/city/{id}")
    public City findOneCity(@PathVariable("id") Long id) {
        return cityService.findCityById(id);
    }

    
    @ApiOperation(value = "保存新增城市的信息",notes = "新增城市对象信息保存")
    @ApiImplicitParam(name ="city",value = "城市信息实体对象",paramType = "body",required = true,dataType = "City")
    @PostMapping(value = "/api/city")
    public void createCity(@RequestBody City city) {
        cityService.saveCity(city);
    }
    
    @ApiOperation(value = "根据id更新对象信息",notes = "根据id更新城市对象信息")
    @ApiImplicitParam(name ="city",value = "城市信息实体对象",paramType = "body",required = true,dataType = "City")
    @PutMapping(value = "/api/city")
    public void modifyCity(@RequestBody City city) {
        cityService.updateCity(city);
    }
    
    @ApiOperation(value = "根据id删除城市的信息",notes = "根据id删除单个城市对象信息")
    @ApiImplicitParam(name ="id",value = "城市信息实体对象主键",paramType = "path",required = true,dataType = "Long")
    @DeleteMapping(value = "/api/city/{id}")
    public void modifyCity(@PathVariable("id") Long id) {
        cityService.deleteCity(id);
    }
}

打开浏览器访问“http://localhost:8080/swagger-ui.html”会看到如下的界面

SpringBoot整合Swagger2

 在输入框中输入id的值后点击”Try it out“按钮,我们可以查看到下面的结果:

SpringBoot整合Swagger2

Swagger2注解说明
@Api:用在类上,说明该类的作用。
    tags = ”说明该类的作用“
@ApiOperation():用在请求的方法上,说明的方法的用户和作用
    value=“说明方法的用途、作用”
    notes="方法的备注说明“
@ApiImplicitParams():用在请求的方法上,表示一组参数说明,可以包含多个@ApiImplicitParam()
@ApiImplicitParam():指定一个请求参数的各个方面

 paramType:参数放在哪个地方

   header 请求参数的获取:@RequestHeader

   query 请求参数的获取:@RequestParam

   path(用于restful接口) 请求参数的获取:@PathVariable

   body(不常用)请求参数的获取:@RequestBody(代码中接收注解)

   form(不常用)

 name:参数名

 dataType:参数类型

 required:参数是否必须传

 value:参数的意思

 defaultValue:参数的默认值
@ApiResponses():用在请求的方法上,表示一组响应。可以包含多个@ApiResponse()
@ApiResponse():用于表示一个错误的响应信息
      code:数字
      message:信息
      response:抛出异常的类      

@ApiModel():用在响应类上,表示一个返回响应数据的信息。
@ApiModelProperty():用在属性上,描述响应类的属性

@ApiModelProperty 这里顾名思义,描述一个model的属性,就是标注在被标注了@ApiModel的class的属性上,这里的value是对字段的描述,example是取值例子,注意这里的example很有用,对于前后端开发工程师理解文档起到了关键的作用,因为会在api文档页面上显示出这些取值来;这个注解还有一些字段取值,可以自己研究,举例说一个:position,表明字段在model中的顺序

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(description = "返回响应数据")
public class RestMessgae {
 
    @ApiModelProperty(value = "错误信息")
    private String message;
    @ApiModelProperty(value = "状态码")
    private String code;
    @ApiModelProperty(value = "返回的数据")
    private Object data;
    // get set
}