文章目录
1. swagger 介绍
OpenAPI 是一个编写 API 文档的规范,然而如果手动去编写 OpenAPI 规范的文档,是非常麻烦的。而 Swagger 就是一个实现了OpenAPI 规范的工具集。
- 号称世界上最流行的Api框架
- RestFul Api 文档在线自动生成工具,Api文档与Api定义同步更新
- 直接运行,可以在线测试API接口
- 支持多种语言:(Java,php等)
2. 快速入门案例
SpringBoot 已经集成了 Swagger,使用简单注解即可生成 swagger 的 API 文档。
引入Swagger2依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
3. 启用Swagger2
方法:在配置类或者启动类加上@EnableSwagger2注解
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@MapperScan("com.why.mapper")
@EnableScheduling //定时任务开启
@EnableSwagger2 //启用Swagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
或者
//配置Swagger
@EnableSwagger2 //用来开启Swagger2
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
4.测试
访问:http://localhost:7777/swagger-ui.html
localhost:7777
换成自己的域名或者端口号
测试成功!
解析:
5. 具体配置
swagge-ui 根据接口自动生成文档说明,不够详细。如果有需要,可以通过注解自定义接口声明。
(1)controller配置
@Api:修饰整个类,描述Controller的作用
@Api(tags = “控制器-hello”)
为接口添加说明信息
以CommentController
为例:
加上 @Api
@Api(tags = “评论”,description = “评论相关接口”)
- 属性介绍:
tags
设置标签 description
设置描述信息
import com.why.constants.SystemConstants;
import com.why.domain.ResponseResult;
import com.why.domain.entity.Comment;
import com.why.service.CommentService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/comment")
@Api(tags = "评论",description = "评论相关接口")
public class CommentController {
@Resource
private CommentService commentService;
@GetMapping("/commentList")
public ResponseResult commentList(Long articleId,Integer pageNum,Integer pageSize){
return commentService.commentList(SystemConstants.ARTICLE_COMMENT,articleId,pageNum,pageSize);
}
}
(2)接口配置
@ApiOperation
:描述一个类的一个方法或一个接口,或者说@ApiOperation(“hello请求”)
是为请求增加说明信息
说明:@ApiOperation(value = "接口中文名",notes = "接口的详细解释")
以CommentController为例:
import com.why.constants.SystemConstants;
import com.why.domain.ResponseResult;
import com.why.domain.entity.Comment;
import com.why.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/comment")
@Api(tags = "评论(CommentController)",description = "评论相关接口")
public class CommentController {
@Resource
private CommentService commentService;
/**
* 文章评论
* @param articleId
* @param pageNum
* @param pageSize
* @return
*/
@GetMapping("/commentList")
@ApiOperation(value = "文章评论列表",notes = "获取一页文章评论")
public ResponseResult commentList(Long articleId,Integer pageNum,Integer pageSize){
return commentService.commentList(SystemConstants.ARTICLE_COMMENT,articleId,pageNum,pageSize);
}
/**
* 添加评论(文章评论或友链评论)
* 注意:这里直接添加即可,展示文章评论或友链评论会从数据库中取出数据判断type区别友链和文章
* 映射就是/comment
* @return
*/
@PostMapping
@ApiOperation(value = "添加评论(文章评论或友链评论)",notes = "添加评论(文章评论或友链评论)这里直接添加即可,展示文章评论或友链评论会从数据库中取出数据判断type区别友链和文章")
public ResponseResult addComment(@RequestBody Comment comment){
return commentService.addComment(comment);
}
/**
* 显示友链评论(分页显示)
* @param pageNum
* @param pageSize
* @return
*/
@GetMapping ("/linkCommentList")
@ApiOperation(value = "友链评论列表",notes = "获取一页友链评论")
public ResponseResult linkCommentList(Integer pageNum,Integer pageSize){
return commentService.commentList(SystemConstants.LINK_COMMENT,null,pageNum,pageSize);
}
}
测试
(3)接口参数
-
一个请求参数:
@ApiImplicitParam(name = “参数名”,value = “参数含义”) -
多个请求参数
@ApiImplicitParams({
@ApiImplicitParam(name = “参数名”,value = “参数含义”),
@ApiImplicitParam(name = “参数名”,value = “参数含义”)
})
import com.why.constants.SystemConstants;
import com.why.domain.ResponseResult;
import com.why.domain.entity.Comment;
import com.why.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/comment")
@Api(tags = "评论(CommentController)",description = "评论相关接口")
public class CommentController {
@Resource
private CommentService commentService;
/**
* 文章评论
* @param articleId
* @param pageNum
* @param pageSize
* @return
*/
@GetMapping("/commentList")
@ApiOperation(value = "文章评论列表",notes = "获取一页文章评论")
@ApiImplicitParams({
@ApiImplicitParam(name = "articleId", value = "文章id"),
@ApiImplicitParam(name = "pageNum", value = "页号"),
@ApiImplicitParam(name = "pageSize", value = "每页大小")
})
public ResponseResult commentList(Long articleId,Integer pageNum,Integer pageSize){
return commentService.commentList(SystemConstants.ARTICLE_COMMENT,articleId,pageNum,pageSize);
}
/**
* 添加评论(文章评论或友链评论)
* 注意:这里直接添加即可,展示文章评论或友链评论会从数据库中取出数据判断type区别友链和文章
* 映射就是/comment
* @return
*/
@PostMapping
public ResponseResult addComment(@RequestBody Comment comment){
return commentService.addComment(comment);
}
/**
* 显示友链评论(分页显示)
* @param pageNum
* @param pageSize
* @return
*/
@GetMapping ("/linkCommentList")
@ApiOperation(value = "友链评论列表",notes = "获取一页友链评论")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "页号"),
@ApiImplicitParam(name = "pageSize", value = "每页大小")
})
public ResponseResult linkCommentList(Integer pageNum,Integer pageSize){
return commentService.commentList(SystemConstants.LINK_COMMENT,null,pageNum,pageSize);
}
}
(4)实体类配置
@ApiModel(description = “添加评论实体类”)为实体类添加说明信息
@ApiModelProperty(notes = “用户名”)为实体类中的属性添加说明信息
注意如果实体类有很多的接口都在使用(尤其是实体类与数据库表进行映射时,因为数据库表属性一般和程序中需要用到的属性不完全一致),这时应该使用Dto(数据传输对象)
AddCommentDto (和comment实体类属性相同)
作用是单独为添加评论的实体类属性在swagger文档中注释
注意,传值时需要使用拷贝给comment实体类
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ApiModel(description = "添加评论dto")
public class AddCommentDto {
private Long id;
//评论类型(0代表文章评论,1代表友链评论)
@ApiModelProperty(notes = "评论类型(0代表文章评论,1代表友链评论)")
private String type;
//文章id
@ApiModelProperty(notes = "文章id")
private Long articleId;
//根评论id
@ApiModelProperty(notes = "根评论id")
private Long rootId;
//评论内容
@ApiModelProperty(notes = "评论内容")
private String content;
//所回复的目标评论的userid
@ApiModelProperty(notes = "所回复的目标评论的userid")
private Long toCommentUserId;
//回复目标评论id
@ApiModelProperty(notes = "回复目标评论id")
private Long toCommentId;
private Long createBy;
private Date createTime;
private Long updateBy;
private Date updateTime;
//删除标志(0代表未删除,1代表已删除)
private Integer delFlag;
}
接口代码:
/**
* 添加评论(文章评论或友链评论)
* 注意:这里直接添加即可,展示文章评论或友链评论会从数据库中取出数据判断type区别友链和文章
* 映射就是/comment
* @return
*/
@PostMapping
public ResponseResult addComment(@RequestBody AddCommentDto addCommentDto){
Comment comment = BeanCopyUtils.copyBean(addCommentDto, Comment.class);
return commentService.addComment(comment);
}
拷贝工具类:
import org.springframework.beans.BeanUtils;
import java.util.List;
import java.util.stream.Collectors;
/**
* 实现需要返回的数据结果的拷贝
*/
public class BeanCopyUtils {
public BeanCopyUtils() {
}
//Class clazz:可以通过反射创建对象
/**
* 单个对象的拷贝
* @param source
* @param clazz
* @param <V>
* @return
*/
public static <V> V copyBean(Object source,Class<V> clazz){
V result = null;
try {
//创建目标对象
result = clazz.newInstance();
//实现属性copy
BeanUtils.copyProperties(source,result);
} catch (Exception e) {
e.printStackTrace();
}
//返回结果
return result;
}
public static <T,V> List<V> copyBeanList(List<T> list, Class<V> clazz){
/**
* 1).stream() 方法表示将原始的 List 集合转换为 Java8 中的 Stream 流对象,以便进行数据处理。
* 2)接着,.map(o -> copyBean(o, clazz)) 方法利用 copyBean 方法将原始集合 list 中的元素 o 转化为目标类型 clazz 的对象,
* 3)并用 Stream 中的 map() 方法逐一进行操作。
* 4)最后,.collect(Collectors.toList())方法将流式处理结果收集起来,生成一个新的列表。
*/
return list.stream()
.map(o -> copyBean(o, clazz))
.collect(Collectors.toList());
}
}
测试
(6)文档信息配置
写一个配置类
SwaggerConfig :
package com.why.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.why.controller"))
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact("团队名", "http://www.why.com", "why.com");
return new ApiInfoBuilder()
.title("博客前台项目")
.description("文档描述")
.contact(contact) // 联系方式
.version("1.1.1") // 版本
.build();
}
}
测试: