SpringBoot结合SpringDoc 带有请求头(token)
一、maven配置:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.5.12</version> </dependency>
二、配置文件OpenApiConfig.class (⚠️:需要修改扫描路径)
import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Contact; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * springDoc-swagger标准配置 * * @author huang cheng * 2021/8/13 */ @Configuration public class SpringDocSwaggerConfig { private static final String basePackage = "com.resume.uniapp.controller";//需要扫描api路径,修改成自己controller文件的路径 private static final String headerName = "Authorization";//请求头名称 @Bean public GroupedOpenApi usersGroup() { return GroupedOpenApi.builder() .group("users") .addOperationCustomizer((operation, handlerMethod) -> { operation.addSecurityItem(new SecurityRequirement().addList(headerName)); return operation; }) .packagesToScan(basePackage) .build(); } @Bean public OpenAPI customOpenAPI() { Components components = new Components(); //添加右上角的统一安全认证 components.addSecuritySchemes(headerName, new SecurityScheme() .type(SecurityScheme.Type.APIKEY) .scheme("basic") .name(headerName) .in(SecurityScheme.In.HEADER) .description("请求头") ); return new OpenAPI() .components(components) .info(apiInfo()); } private Info apiInfo() { Contact contact = new Contact(); contact.setEmail("1003816735@qq.com"); contact.setName("cheng"); contact.setUrl("https://blog.csdn.net/qq_42495847?spm=1000.2115.3001.5343"); return new Info() .title("sunnyDay-swagger文档") .version("1.0") .contact(contact) .description("博客请关注:https://blog.csdn.net/qq_42495847?spm=1000.2115.3001.5343") .license(new License().name("Apache 2.0").url("http://springdoc.org")); } }
三、Controller简单注释
@Tag(name = "用户基本信息") @RestController @RequestMapping("/user") public class UserInfoController { @Resource private UserInfoService userService; @Operation(summary = "查询全部数据") @GetMapping("/selectAll") public R selectAll(){ R r = new R(); r.setData(userService.selectAll()); return r; } }
参考http://l.lvovl.cn/swagger-springdoc基础使用/