跳到主要内容

Springboot接入Swagger

参考资料

引入依赖

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.9</version>
</dependency>

此时进行构建即可在 /swagger-ui/index.html 访问到 Swagger API 文档。

配置 Swagger

springdoc:
api-docs:
# 是否开启文档功能
enabled: true
# api json 文档
path: /v3/api-docs
swagger-ui:
# 自定义swagger前端请求路径,访问 /docs 会自动重定向到swagger页面
path: /docs
# 默认查询的 api json 地址
config-url: /v3/api-docs
# 包扫描路径
packages-to-scan: com.kenko.app.controller
package com.kenko.app.config;

import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;

@OpenAPIDefinition(
info = @Info(
title = "我的APP后端",
version = "1.0",
contact = @Contact(name = "AkagiYui", url = "https://akagiyui.com")
),
security = @SecurityRequirement(name = "JWT"),
externalDocs = @ExternalDocumentation(
description = "GitHub页面",
url = "https://github.com/AkagiYui"
)
)
@SecurityScheme(type = SecuritySchemeType.HTTP, name = "JWT", scheme = "bearer", in = SecuritySchemeIn.HEADER)
public class SwaggerConfig {
}

编写 API 注解

@RestController
@RequestMapping("/user")
@Tag(name = "user", description = "用户接口")
public class UserController {
@PostMapping("/login")
@Operation(summary = "登录", description = "获取 JWT token")
public String getUserJwt(@RequestBody LoginVO teacher) {
return "This is JWT.";
}
}