Swagger使用
Posted 诺浅
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swagger使用相关的知识,希望对你有一定的参考价值。
为什么写这篇文章
如果你打开百度,搜索Swagger使用,网上说引入各种包的都有,访问的路径也是千奇百怪,你始终搞不清楚到底需要引入哪些包,访问路径到底是哪个。究其原因,是因为springboot的版本不同,导致的配置方式也不同。这篇文章跟你一次性讲清楚
Swagger使用
非springboot项目或者老的springboot项目方式引包
<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>
访问路径:http://ip:port/swagger-ui.html
新的方式
上诉这种方式是老的方式,后来springboot官方搞了个新包springfox-boot-starter
,新包中集成了springfox-swagger2
,springfox-swagger-ui
.
所以我们只需要在项目中引用
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
然后启动,哦豁,报错了
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
此时需要在启动类上加注解@EnableWebMvc
启动正常了
访问http://ip:port/swagger-ui/index.html
如果访问这个路径打不开,需要配置一下静态资源处理
然后就打开了Swagger自带的页面
配置knife4j
u1s1,Swagger自带的接口页面真的是丑且不直观,此时配置一下knife4j
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
访问:http://localhost:8080/doc.html
需要配置下资源处理
@SpringBootApplication
@EnableWebMvc
public class DemoApplication implements WebMvcConfigurer
public static void main(String[] args)
SpringApplication.run(DemoApplication.class, args);
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
刷新,就打开了
以上是关于Swagger使用的主要内容,如果未能解决你的问题,请参考以下文章