前言
上一章节Swagger使用起来对raw格式支持不友好,直接升级到knife4j,本文采用knife4j-spring-boot-starter 3.0版本,在Springboot2.7基础上增加knife4j功能。
1、环境配置
1.1、导入依赖包
<!-- Spring Boot 项目starter,快速使用knife4j增强文档 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency>
1.2、在config目录下增加SwaggerConfig 配置
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; 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.context.annotation.Import; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; 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 springfox.documentation.swagger2.annotations.EnableSwagger2; import java.lang.reflect.Field; import java.util.List; import java.util.stream.Collectors; /** * Knife4j 3.X 配置类. * Knife4j 访问首页: http://localhost/doc.html# * @author Kelvin * @date 2023-5-21 23:43:39 */ @EnableKnife4j @Configuration @EnableSwagger2 @Import(BeanValidatorPluginsConfiguration.class) // 在 Swagger 3.X 以下版本报错时可以加此注解解决,但是在3.X版本以上的,加此注解会导致页面无法打开 //@EnableWebMvc public class SwaggerConfig { private static final String SWAGGER_TITLE = "XXX项目 API 接口文档"; private static final String VERSION = "3.0.3"; @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) .enable(true) // .useDefaultResponseMessages(false) .apiInfo(apiInfo()) .groupName("3.X 版本") .select() // 方式一: 配置扫描 所有想在swagger界面的统一管理接口,都必须在此包下 // .apis(RequestHandlerSelectors.basePackage("com.xxx.controller")) // 方式二: 只有当类上有 @RestController 注解时才能生成对应的接口文档 .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) // 方式三: 只有当方法上有 @ApiOperation 注解时才能生成对应的接口文档 // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(SwaggerConfig.SWAGGER_TITLE) .description("# XXX项目API接口文档简介") .termsOfServiceUrl("http://127.0.0.1/#/login") .contact(new Contact("联系人", "联系人网站", "联系人邮箱")) .version(SwaggerConfig.VERSION) .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"); assert field != null; field.setAccessible(true); return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } }; } }
1.3、为knife4j配置ResourceHandlers
含【Swagger3资源配置】、【静态资源配置】
如果配置有拦截器,需要把"/doc.html"、“/favicon.ico”、“/swagger-resources/" 、 "/v3/” 、 "/v2/“、”/webjars/"等加入放行链。
@Configuration public class MyWebMvcConfig extends WebMvcConfigurationSupport { /** * 资源映射 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //加载public文件夹数据 registry.addResourceHandler("/public/**") .addResourceLocations("classpath:/public/"); //加载static文件夹数据 registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); // swagger配置 registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } /** * 注册自定义的拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/**")//拦截所有请求 .excludePathPatterns("/","/user/login","*.html","/static/**","/doc.html", "/favicon.ico","/swagger-resources/**" , "/v3/**" , "/v2/**" , "/webjars/**");//放行的请求; } }
2、应用
同上章节第2部分【《springboot实战》 第十二章 SpringBoot整合swagger-bootstrap-ui】