Swagger3详细配置流程
之前一直使用的swagger2,这次切换成了swagger3,感觉挺好,具体可以看下方配置流程
1. 引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
只需要引入这一个
2. yaml配置
springfox:
documentation:
enabled: true #定义是否显示接口界面,false即关闭
3.配置类
package com.tencentbridge.swagger3;
import io.swagger.annotations.ApiOperation;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author xupt
*/
@Configuration
public class Swagger3Config {
/**
* 定义的token名字
*/
private static final String TOKEN_NAME = "Authorization";
@Bean
public Docket createRestApi() {
//存储用户必须提交的参数
List<SecurityScheme> apiKeys = Collections.singletonList(HttpAuthenticationScheme.JWT_BEARER_BUILDER
.name(TOKEN_NAME)
.build());
//如果用户JWT认证通过,则在Swagger中全局有效
AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] scopeArray = {scope};
//存储令牌和作用域
SecurityReference reference = new SecurityReference(TOKEN_NAME, scopeArray);
ArrayList<SecurityReference> referenceArrayList = new ArrayList<>();
referenceArrayList.add(reference);
SecurityContext context = SecurityContext.builder().securityReferences(referenceArrayList).build();
ArrayList<SecurityContext> contextArrayList = new ArrayList<>();
contextArrayList.add(context);
return new Docket(DocumentationType.OAS_30)
//配置api文档元信息
.apiInfo(apiInfo())
// 选择哪些接口作为swagger的doc发布
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(apiKeys)
.securityContexts(contextArrayList);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("改色系统接口文档")
.description("贴膜改色系统后端接口")
.contact(new Contact("Xpt", "https://tencentbridge.com", "miniprogram@88.com"))
.version("1.0")
.build();
}
}
4.使用
package com.tencentbridge.swagger3;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = "接口展示")
public class TestController {
@ApiOperation("查询测试")
@GetMapping("test")
public String test() {
return "hello world";
}
}
5.效果
访问地址:http://localhost:8080/swagger-ui/
6.完整demo
- 上一篇: vue使用normalize.css重置浏览器样式
- 下一篇: 没有了