springboot2.6.x 集成swagger2(knife4j)
不需要网上说的需要在配置文件中加入:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
或者启动类加上@EnableWebMvc
实现方式如下:
引入pom:
<!-- swagger -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.10.5</version>
</dependency>
package com.yoocheese.library.web.config.swagger;
import cn.hutool.core.collection.CollectionUtil;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.util.List;
/**
* @Description
* @Author AF
* @Version 1.0.0
* @Date 2023/11/30
*/
@Import(BeanValidatorPluginsConfiguration.class)
@EnableSwagger2WebMvc
@EnableKnife4j
public abstract class AbstractSwaggerConfig {
// 这个是为了解决swagger和springboot2.6.x以上版本不兼容,Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
@Bean
public SpringFoxHandlerProviderBeanPostProcessor springFoxHandlerProviderBeanPostProcessor() {
return new SpringFoxHandlerProviderBeanPostProcessor();
}
@Bean
public Docket docket() {
SwaggerProperties swaggerProperties = swaggerProperties();
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo(swaggerProperties))
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securityContexts(CollectionUtil.newArrayList(securityContext()))
.securitySchemes(CollectionUtil.newArrayList(apiKey()));
}
public ApiInfo apiInfo(SwaggerProperties swaggerProperties ) {
return new ApiInfoBuilder()
.description(swaggerProperties.getDescription())
.version(swaggerProperties.getVersion())
.title(swaggerProperties.getTitle())
.contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
.build();
}
private ApiKey apiKey() {
return new ApiKey("Bearer", "Authorization", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return CollectionUtil.newArrayList(new SecurityReference("Bearer", authorizationScopes));
}
public abstract SwaggerProperties swaggerProperties();
}
定义SpringFoxHandlerProviderBeanPostProcessor
package com.yoocheese.library.web.config.swagger;
import cn.hutool.core.util.ReflectUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Description
* @Author AF
* @Version 1.0.0
* @Date 2023/11/30
*/
public class SpringFoxHandlerProviderBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider) {
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) {
return (List<RequestMappingInfoHandlerMapping>) ReflectUtil.getFieldValue(bean, "handlerMappings");
}
}
定义swaggerProperties:
package com.yoocheese.library.web.config.swagger;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* Swagger自定义配置
*
* @author macro
* @date 2020/7/16
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Builder
public class SwaggerProperties {
/**
* 文档标题
*/
private String title;
/**
* 文档描述
*/
private String description;
/**
* 文档版本
*/
private String version;
/**
* 文档联系人姓名
*/
private String contactName;
/**
* 文档联系人网址
*/
private String contactUrl;
/**
* 文档联系人邮箱
*/
private String contactEmail;
}
启动swagger:
package com.yoocheese.test.config;
import com.yoocheese.library.web.config.swagger.AbstractSwaggerConfig;
import com.yoocheese.library.web.config.swagger.SwaggerProperties;
import org.springframework.context.annotation.Configuration;
/**
* @Description
* @Author AF
* @Version 1.0.0
* @Date 2023/11/30
*/
//@Configuration
@Configuration
public class SwaggerConfig extends AbstractSwaggerConfig {
@Override
public SwaggerProperties swaggerProperties() {
return SwaggerProperties.builder()
.title("测试")
.contactEmail("343663190@qq.com")
.contactName("AF")
.version("V1.0")
.build();
}
}
knife4j:
enable: true //启动knife4j
basic: // 启动账号密码简单访问swagger文档
username: af
password: 123456
enable: true
最后访问地址:
http:ip+port/doc.html
http:ip+port/swagger-ui.html
评论区