Swagger&Knif4j接口文档集成
Swagger&Knif4j接口文档集成
为什么使用?
在开发过程中,接口文档是非常重要的一环,在 Spring Boot 中,我们可以通过集成第三方来实现接口文档的自动生成。通过注解来描述接口,然后根据这些注解自动生成接口文档,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。常用的接口文档,有Swagger和Knife4j,推荐Knife4j 。
1.导入依赖
<!--springfox swagger官方Starter-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--knife4j-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2.增加config配置
package com.wyoung.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
/**
* @className:Swagger2Config
*/
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.wyoung.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI演示")
.description("wyoung-tiny")
.contact(new Contact("wyoung", null, null))
.version("1.0")
.build();
}
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}
3.配置路径匹配策略
如果 springboot version >= 2.6,需要添加如下配置
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
原因:
Spring MVC 的路径匹配策略是 ant-path-matcher
,而 Spring Boot 2.6.x版本的默认匹配策略是 path-pattern-matcher
,这就导致启动时报错,错误内容信息:
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
...
4.配置是否屏蔽文档接口
在文件application.yml
配置,生产环境注意防止暴露接口文档(production设置为true)
knife4j:
# 开启增强配置
enable: true
# 是否屏蔽接口文件(true=屏蔽,false=不屏蔽)
production: false
5.启动项目,输入地址
地址:http://localhost:8080/swagger-ui.html