Swagger是什么
现在项目基本都采用前后端分离模式开发,在前后端分离人不分离情况下还好,正常前后端分离需要沟通返回的实体类型、请求方式等内容。传统方式一般由后端人员自己编写文档,但缺点也很明显,后端更新时文档不能得到及时的更新,编写花费时间多。而使用了Swagger后能极大提高工作效率,比传统手动编写更快,实时性更强,根据代码字典生成API文档,且跨语言性,不仅仅支持java
项目集成Swagger
-
注意点:在springboot2.6版本后集成swagger2会报错空指针,需要配置匹配策略或者配置@EnableWebMvc
解决方法:
-
在application.yaml文件配置映射匹配策略
spring: mvc: pathmatch: matching-strategy: ant_path_matcher
-
启动类添加@EnableWebMvc注解
@SpringBootApplication @EnableScheduling @EnableSwagger2 @EnableWebMvc public class blogApplication { public static void main(String[] args) { SpringApplication.run(blogApplication.class,args); } }
-
更换版本,降低到2.6以下
原因:
springboot2.0后请求路径与 Spring MVC 处理映射匹配的默认策略已从AntPathMatcher更改为PathPatternParser。
-
springboot2.6前
public static class Pathmatch { private MatchingStrategy matchingStrategy = MatchingStrategy.ANT_PATH_MATCHER; }
-
springboot2.6后
public static class Pathmatch { private MatchingStrategy matchingStrategy = MatchingStrategy.PATH_PATTERN_PARSER; }
-
引入依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
-
使用@EnableSwagger注解在启动类上启用Swagger
@SpringBootApplication @EnableScheduling @EnableSwagger2 public class blogApplication { public static void main(String[] args) { SpringApplication.run(blogApplication.class,args); } }
-
访问路径
默认访问路径为:服务器域名+端口号+/swagger-ui.html
-
自定义编辑API文档信息
-
controller编辑
//在整个Controller类上添加 @Api(tags = "文章接口",description = "文章相关的接口")
-
service编辑
//在每个接口功能方法上添加 @ApiOperation(value = "文章详情",notes = "通过前端传入id查询文章详情")
-
service参数配置
//与上同 @ApiImplicitParams({ @ApiImplicitParam(name = "id",value = "文章id") })
-
实体参数配置
一般直接与DAO层的实体类不建议使用此注解,使用DTO传输对象标注此对象。当添加或修改某数据库表时,传入的实体都为一个实体类对象,那么注解的描述就不通用
//实体类上添加 @ApiModel(description = "评论实体类")
-
配置文件参数配置
//添加配置文件注解,将方法注入容器 @Configuration public class SwaggerConfig { @Bean public Docket customDocket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.cg.controller"))//包扫描路径 .build(); } private ApiInfo apiInfo(){ Contact se7en = new Contact("se7en", "www.baidu.com", "cg@163.com"); return new ApiInfoBuilder() .title("文档标题") .description("描述") .contact(se7en) //联系 .version("版本信息") .build(); } }
参考来源
https://blog.csdn.net/qq_33334411/article/details/125655201
-