springboot 2.7 整合swagger3.0(knife4j)

1,引入依赖


   com.github.xiaoymin
   knife4j-spring-boot-starter

springboot 版本


    org.springframework.boot
    spring-boot-starter-parent
    2.7.5

2,配置文件

因为版本问题会出现异常导出启动失败

Failed to start bean 'springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

springboot 2.7 整合swagger3.0(knife4j)_第1张图片

 配置 springfoxHandlerProviderBeanPostProcessor 解决上面报错问题



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.servlet.mvc.method.RequestMappingInfoHandlerMapping;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.constraints.NotNull;

import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.SecurityScheme;
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 static com.google.common.collect.Lists.newArrayList;

/**
 * Swagger配置
 *
 * @author : zl [email protected]
 * @since : 2022/12/10
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@AllArgsConstructor
public class SwaggerConfig {

    public static final String TOKEN_HEADER = "Authorization";

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //加了ApiOperation注解的类,生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //包下的类,生成接口文档
                .paths(PathSelectors.any())
                .build()
                .directModelSubstitute(java.util.Date.class, String.class)
                .securitySchemes(security());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("work-order-desktop")
                .description("work-order-desktop文档")
                .termsOfServiceUrl("http://www.zuitimes.com")
                .version("1.x")
                .build();
    }

    private List security() {
        return newArrayList(
                new ApiKey(TOKEN_HEADER, TOKEN_HEADER, "header")
        );
    }


    /**
     * 解决springBoot2.7 与swagger不兼容问题
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private  void customizeSpringfoxHandlerMappings(List mappings) {
                List copy = mappings.stream()
                                       .filter(mapping -> mapping.getPatternParser() == null)
                                       .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    assert field != null;
                    field.setAccessible(true);
                    return (List) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }

}

3,springboot 配置

knife4j:
  enable: true #开启增强配置
  basic: #基本的登录认证
    enable: true
    username: admin
    password: 123456

springboot 2.7 整合swagger3.0(knife4j)_第2张图片

 spring:
  mvc:
    path match:
        matching-strategy: ant_path_matcher

springboot 2.7 整合swagger3.0(knife4j)_第3张图片

这里要注意是 path match 不是 path_match 

可选配置

application-prod.yml
production: true #开启生产环境屏蔽

4,启动项目,访问地址:ip:port/doc.html 

你可能感兴趣的:(spring,boot,后端,java)