Swagger3使用
一、Swagger是什么
Swagger是一个辅助我们写开发文档的一个 ,做一些配置和代码注解就可以实现API文档
二、使用步骤
1.引入pom依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2.写一个配置类
package cn.lyz.service.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.*;
/**
* Created by teacher ZHANG on 2022/2/12
* 启用swagger:接口文档+调度工具
* @author liyuzhen
*/
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
Docket build = new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
return build;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("博客内容接口")//标题
.description("更多请咨询服务开发者。")
.contact(new Contact("LiYuZhen", "https://blog.csdn.net/qq_52288555", "zhangsan@163.com"))
.version("1.0")
.build();
}
}
3.写对应的controller类
@Api(tags="博客控制层")
@RestController
@RequestMapping("/articles")
public class ArticleController {
@Resource
private ArticleService articleService;
@ApiOperation(value = "文章删除")
@ApiImplicitParam(name = "articleId", value = "文章id", required = true, dataType = "Integer", paramType = "path")
@DeleteMapping("/{articleId}")
public Boolean deleteArticle(@PathVariable Integer articleId) {
return articleService.removeById(articleId);
}
@ApiOperation(value = "文章查询(分页)")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNumber", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "pageSize", value = "条数", dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "categoryId", value = "分类Id", dataType = "Integer", paramType = "query")
})
@GetMapping("")
public PageBean<Article> getArticles(Integer pageNumber, Integer pageSize, Integer categoryId) {}
注解详解
@Api():打在类上 属性 tags : 对类的详细介绍
@ApiOperation() :打在方法上 属性 value 对方法的详细介绍
@ApiImplicitParam() 打在方法上
属性
name:方法名称 (String)
values : 方法的介绍 (String)
required : 方法是否必须传 (Boolean)
dataType :参数类型String()
paramType :参数是通过什么方式传过来的
path : 路径参数
body :请求负载
query:问号传值
4.访问Swagger
端口号对应服务器端口
http://localhost:8090/swagger-ui/index.html#/
5.错误解决
如果在启动时报错
1.解决办法
(1).在启动类上加入注解
@EnableWebMvc
(2).或者在配置文件中加入配置
spring:
#此配置为解决swagger启动报错
mvc:
pathmatch:
matching-strategy: ant_path_matcher