目录
使用背景
一、搭建SpringBoot框架
二、添加依赖
三、添加配置
四、创建两个配置类
开始测试
添加说明
效果
因为前后端分离的原因,接口文档越来越重要,它上面记录着 连接前后端的路径、访问方式、字段
自己写接口文档-麻烦
所以用Swagger2,它可以自动生成接口文档。
Swagger2官方说明文档:http://springfox.github.io/springfox/docs/2.9.2/#getting-started
SpringBoot框架快速入门搭建Hello Worldhttps://blog.csdn.net/KangYouWei6/article/details/127018638?spm=1001.2014.3001.5501
在pom.xml中加上
io.springfox
springfox-swagger-ui
2.9.2
io.springfox
springfox-swagger2
2.9.2
将下面修改成自己项目使用的
尤其是包那一块,要修改成自己对应的controller层路径
#Swagger2接口文档
#下面的根据自己的项目来写
#最重要的事basePackageRest,后面写的是controller层的路径
swagger:
title: 校园管理系统的API
description: 作者:康有为 时间:2022/09/25
version: 1.0
contactName: lxt
contactEmail: www.baidu.com
contactUrl: www.bilibili.com
basePackageRest: com.kyw.controller
termsOfServiceUrl:
在com.kyw.config下创建 SwaggerProperties 的类文件
package com.kyw.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "swagger")
@Data
public class SwaggerProperties {
private String title;
private String contactName;
private String contactUrl;
private String contactEmail;
private String version;
private String description;
private String basePackageRest;
private String termsOfServiceUrl;
}
在com.qcby.config下创建 SwaggerConfig 的类文件
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private SwaggerProperties swaggerProperties;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("REST接口")
.apiInfo(apiInfo())
.select()
// 配置自动扫描那些包下类型生成接口文档
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackageRest()))
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperties.getTitle())
//创建人
.contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(),swaggerProperties.getContactEmail()))
//版本号
.version(swaggerProperties.getVersion())
//描述
.description(swaggerProperties.getDescription())
.build();
}
}
到这里配置完毕了!
直接访问
http://localhost:8081/swagger-ui.html
会显示下面的效果
在controller类的上面加上注解来说明
// controller类
@Api(tags = {"登录模块"})
在controller类的方法上面添加注解来说明方法
// 方法
@ApiOperation("登录接口")
在实体类(entity层)的上面加上注解来说明实体类
// 实体类
@ApiModel("用户实体")
在实体类字段的上面加上注解用来说明字段
@ApiModel("学生实体")
public class Student {
@ApiModelProperty(value = "学生id")
private Integer id;
@ApiModelProperty(value = "学生姓名")
private String name;
@ApiModelProperty(value = "学生学号")
private String sno;
@ApiModelProperty(value = "学生性别")
private String sex;
在controller的方法的上面加上注解来说明方法的参数
// 参数
@ApiImplicitParams(
{@ApiImplicitParam(name = "id",
value = "用户的id", required = true,
dataType = "Long", paramType = "header")
,
@ApiImplicitParam(name = "name",
value = "用户的name", required = true,
dataType = "String", paramType = "header")
}
)
喜欢的话点个吧,谢谢你的观看