Springboot2.7整合Swagger3
Springboot2.7.x改动较大,Swagger3.0.0也是改动较大,两个一掺和,一堆问题就出来了。
1.引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
原先的springfox-swagger-ui
依赖似乎不需要了。
2.10.x版本中的@EnableSwagger2
注解被移除了,3.0.0又添加回来了,但是我这边@EnableSwagger2
注解不起作用,还是换成springfox-boot-starter
依赖吧。
参考链接:Replace @EnableSwagger2 after update to latest version - stackoverflow
2.添加配置
在项目中新建 SwaggerConfig 配置文件
package com.subaru.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().build();
}
}
原先的@EnableSwagger2
注解我换成了springfox-boot-starter
依赖。
3.修改yml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
Springfox 假设 Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x及以后版本的默认匹配策略是 path-pattern-matcher,不修改会造成下方documentationPluginsBootstrapper
报错。
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException...
参考链接:Spring Boot 2.6.x整合Swagger启动失败报错问题解决(治标还治本) - csdn
4.编写测试类
package com.subaru.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Get Hello";
}
@PostMapping("/world")
public String world() {
return "Post World";
}
}
5.启动访问
访问http://localhost:8080/swagger-ui/index.html即可看到新版swagger界面,至此整合结束。
作者:Subaru
出处:https://www.cnblogs.com/Subaru/p/16478402.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!