SpringBoot集成Knife4j
Knife4j简介
Knife4j 官网地址:https://doc.xiaominfo.com/
knife4j 是为Java MVC框架集成Swagger生成Api文档的增强解决方案。
Knife4j 的前身是swagger-bootstrap-ui,是一个纯swagger-ui的ui皮肤项目。
取名knife4j是希望她能像一把匕首一样小巧、轻量,并且功能强悍,更名也是希望把她做成一个为Swagger接口文档服务的通用性解决方案,不仅仅只是专注于前端Ui前端。
引入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
添加yml配置
knife4j:
# 是否开启Swagger
enabled: true
# 请求前缀
pathMapping: /dev-api
# 是否开启Knife4j增强模式,默认是 false
enable: true
查看更多增强模式配置:https://doc.xiaominfo.com/docs/features/enhance
配置Knife4j
@Configuration
@EnableKnife4j
public class Knife4jConfig
{
/** 是否开启Swagger */
@Value("${knife4j.enabled}")
private boolean enabled;
/** 设置请求的统一前缀 */
@Value("${knife4j.pathMapping}")
private String pathMapping;
/**
* 创建API
*/
@Bean
public Docket createRestApi()
{
return new Docket(DocumentationType.OAS_30)
// 是否启用Swagger
.enable(enabled)
// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo())
// 分组名称
.groupName("China")
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
// .apis(RequestHandlerSelectors.basePackage("com.cn.project.tool.swagger"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
/* 设置安全模式,swagger可以设置访问token */
// .securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping(pathMapping);
}
/**
* 安全模式,这里指定token通过Authorization头请求头传递
*/
private List<SecurityScheme> securitySchemes()
{
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
return apiKeyList;
}
/**
* 安全上下文
*/
private List<SecurityContext> securityContexts()
{
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(o -> o.requestMappingPattern().matches("/.*"))
.build());
return securityContexts;
}
/**
* 默认的安全上引用
*/
private List<SecurityReference> defaultAuth()
{
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo()
{
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("后台管理系统_接口文档")
// 描述
.description("用于XXX,具体包括XXX,XXX模块...")
// 作者信息
.contact(new Contact("hviger", null, null))
// 版本
.version("1.0.1")
.build();
}
}
放行Knife4j请求
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
使用Knife4j注解标记接口
@Api(tags = "测试路由")
@RestController
@RequestMapping("/test")
public class TestController {
@ApiOperation("测试get")
@ApiImplicitParam(name = "name", value = "姓名", required = true)
@GetMapping("test1")
public String test1(@RequestParam(value = "name") String name) {
return "hello," + name;
}
@ApiOperation("测试post")
@PostMapping("test2")
public String test2(@RequestBody TestEntity testEntity) {
return testEntity.getName() + ":" + testEntity.getSex();
}
}
@ApiModel
@Data
public class TestEntity {
@ApiModelProperty(value = "姓名", required = true)
private String name;
@ApiModelProperty(value = "性别", required = true)
private String sex;
}