Swagger2
是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful
风格的 Web
服务的接口文档。
进一步说,这个接口文档就是写给前端用的。有时候后端可能会忘记编写接口文件,那么Swagger2
就帮后端开发者写。
这里导入了两个依赖包,第二个依赖包主要是访问swagger2
的UI
界面
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
这个配置类的写法比较固定,其中getApiInfo()
方法主要设置接口文档的一些信息,包括标题、描述以及版本等。api()
这个Bean
写法比较固定,其中basePackage
中的地址不必要搞错,针对于不同接口,更换不同地址。
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.rql.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo getApiInfo(){
Contact contact = new Contact("name", "https://blog.csdn.net/qq_42569028?type=blog", "1476804025@qq.com");
return new ApiInfoBuilder()
.title("标题:图书管理系统")
.description("描述:对图书进行增删改查操作")
.version("版本:项目版本V1.0")
.contact(contact)
.build();
}
}
@Api
:修饰整个类,描述Controller的作用
tags
:“说明该类的作用”
@RestController
@RequestMapping("/books")
@Api(tags = "图书管理系统")
public class BookController {
@ApiOperation
:对类中的方法进行描述
value
=“说明方法的作用”
notes
=“方法的备注说明”
@ApiImplicitParams
:描述由多个 @ApiImplicitParam
注解的参数组成的请求参数列表
@ApiImplicitParam
:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
dataType :参数类型,默认String,其它值dataType=“int”
defaultValue:参数的默认值
paramType:参数放在哪个地方
header --> 请求参数的获取:@RequestHeader
query --> 请求参数的获取:@RequestParam
path(用于restful接口)–> 请求参数的获取:@PathVariable
body(请求体)–> @RequestBody User user
form(普通表单提交)
@GetMapping("{pageNo}/{pageSize}")
@ApiOperation("分页查询数据信息")
@ApiImplicitParams(
{@ApiImplicitParam(name = "pageNo",value = "当前所在的页数"),
@ApiImplicitParam(name = "pageSize",value = "分页的大小"),
@ApiImplicitParam(name = "book",value = "书籍信息")
})
public R getPages(@PathVariable Integer pageNo, @PathVariable Integer pageSize,Book book){
@ApiModel
:用对象来接收参数时,用于描述对象(实体类中的注解)
(这种一般用在post创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )
@ApiProperty
:用对象接收参数时,描述对象的一个字段(实体类中属性的注解)
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "书籍信息")
public class Book {
private Integer id;
@ApiModelProperty(value = "书籍类型")
private String type;
@ApiModelProperty(value = "书籍名称")
private String name;
@ApiModelProperty(value = "书籍描述")
private String description;
private Integer deleted;
}
@ApiResponses
:方法返回对象的说明
@ApiResponse
:每个参数的说明
code
:数字,例如400
message
:信息,例如"请求参数没填好"
@ApiResponses({
@ApiResponse(code = 200,message = "成功获取书籍信息"),
@ApiResponse(code=400,message = "查询逻辑有问题")
})
public R getById(@PathVariable Integer id){
return new R(true,bookService.getById(id));
}
@ApiIgnore:
接口方法注解,添加此注解的方法将不会生成到接口文档中
访问地址:http://localhost:8081/swagger-ui.html