zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

SpringBoot集成Swagger2

2023-04-18 16:05:23 时间

importorg.springframework.context.annotation.Configuration;

importspringfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration   //配置类

@EnableSwagger2  //启动Swagger2的自动配置1 引言

什么是Swagger:

Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。简单来说,Swagger是一个功能强大的接口管理工具,并且提供了多种编程语言的前后端分离解决方案。

Swagger的作用:

  1. 支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,节约了手写文档的时间。
  2. 提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

2 问题

如今前后端通过API进行交互,前后端相对独立且松耦合。会产生前后端集成,前端或者后端无法做到“及时协商,尽早解决”,最终导致问题集中爆发。

3 方法

1.新建SpringBoot-web项目

2.导入Swagger2依赖

<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency>

3.编写controller测试,进行测试运行。

import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping("/test") public String test(){ return "Hello,World"; } }

运行结果:

4.编写一个配置类-SwaggerConfig来配置 Swagger2

5.添加相应注解

import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration //配置类 @EnableSwagger2 //启动Swagger2的自动配置

问题:

启动项目后发现,项目抛出以下错误:

Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

启动Bean失败,原因是我们配置了Swagger类后却没有继承DelegatingWebMvcConfiguration Java 配置类。

导致项目出错。

解决方法:

在启动类加上@EnableWebMvc和@EnableOpenApi注解即可解决。

@EnableWebMvc是使用Java 注解快捷配置Spring Webmvc的一个注解。

在使用该注解后配置一个继承于WebMvcConfigurerAdapter的配置类即可配置好Spring Webmvc。

运行:

访问http://localhost:8080/swagger-ui/index.html,即可以看到Swagger页面

4 结语

本文对SpringBoot集成Swagger2做了简单的介绍,以及配置文件中所出现的问题进行了简单的讲解。

实习编辑:李欣容

稿件来源:深度学习与文旅应用实验室(DLETA)