想必大家之前不愿意用swagger一定是因为它的配置极其繁琐,但是配置好了swagger确实较postman好用,传统的SpringBoot使用Swagger时配置及其繁琐,随着SpringBoot的不断更新,SpringDoc整合了Swagger,并且提供了非常简洁的整合方式
1、添加SpringDoc的依赖:
<!--添加springDoc依赖-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-spring-boot-2-webmvc</artifactId>
<version>3.1.5</version>
</dependency>
注意上述的版本适合于SpringBoot2.6.2版本,框架版本不同时可能会爆启动错误!!
2、然后在SpringBoot的yml文件中,简单定义SpringDoc的基本设置
springdoc:
api-docs:
enabled: true
path: /你自己的项目名称.html
swagger-ui:
path: /swagger-ui.html
disable-swagger-default-url: on
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
3、创建一个配置类,加一些注解。
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.context.annotation.Configuration;
@Configuration
@OpenAPIDefinition(
info = @Info(
//参数的内容都是根据自己的项目自己起的
title = "emos-api",
description = "Emos管理系统的后端Java项目",
version = "1.0"
)
)
//为Swagger整合JWT支持,项目没有令牌模块下面这个注解可以不写
@SecurityScheme(
name = "Token",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer"
)
public class SwaggerConfig {
}
4、创建controller层的一个类即可测试:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
@Tag(name = "登录模块")//方法的显示标题
public class deletes {
@PostMapping("/test")
//参数用于提示用户这个接口是干什么的
@Operation(summary = "测试Swagger")
public String test() {
return "测试Swagger成功";
}
}
5、打开下面这个网址,然后输入在文本框中输入第二部的第四行的“/你的项目名称.html”即可访问,我给项目起的名字是study,所以我应该输入/study.html
http://127.0.0.1:8080/yml配置名称/swagger-ui/index.html?configUrl=/yml配置名称/yml配置名称.html/swagger-config
所以我的链接地址是:
http://127.0.0.1:8080/study/swagger-ui/index.html?configUrl=/study/study.html/swagger-config
继续向下翻就可以看到刚刚自己定义的方法啦。