当我们写了n个接口的时候,管理起来其实是一件很麻烦的事,我们总不可能看着自己的controller层一个一个对应的看吧?不过这对于Java程序员来说也许并不难,但是如果对于前端人员来说,这很可能是天书。第一太不直观,第二不够具体。对于接口的描述,无非就是描述它的url,它的请求方式,以及相应数据,只有了解了这些,前后端才能更好进行配合,实现前后端分离的必备神器。
那么今天要介绍一种工具就是为了来解决这种场景的。当你想要很好地管理你的接口时,你只需要:
第一步:
导入jar包,添加依赖到maven当中:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
一个是swagger2本身,还有一个是ui。两者都需要导入。
第二步:
编写swagger2配置类:
在config软件包中创建一个Swagger2Config:
package com.wxy.controller;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration//代表是一个配置类,让sping扫描
@EnableSwagger2//开启swagger2
public class Swagger2Config {
}
只要配置完以上两项基本就可以了,但是有些时候你可能会出现以下的报错:
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
那是因为:
Springboot2.6以后将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错 !所以我这时候需要在yml文件中进行以下配置
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
配置完成之后,启动Application类,启动springboot工程,然后访问:
localhost:8080/swagger-ui.html
如果出现类似以下页面则成功:
从上面的图就可以很直观的看出各类接口的请求方式以及请求路径,而且他还帮你分好类了,可以更好了解与管理自己的接口了!