importorg.springframework.context.annotation.Configuration;
importspringfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration //配置类
@EnableSwagger2 //启动Swagger2的自动配置1 引言
什么是Swagger:
Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。简单来说,Swagger是一个功能强大的接口管理工具,并且提供了多种编程语言的前后端分离解决方案。
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)
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有