美文网首页
SpringBoot2.7.6整合Swagger3

SpringBoot2.7.6整合Swagger3

作者: 曹大大 | 来源:发表于2024-06-05 14:00 被阅读0次

    pom文件

     <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>3.0.3</version>
    </dependency>
    

    application.yml

    # 启动报错需要修改以下mvc配置 Failed to start bean 'documentationPluginsBootstrapper'
    # Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的PathPatternMatcher。
    spring:
      mvc:
        pathmatch:
          matching-strategy: ant_path_matcher
    swagger:
      # 是否开启swagger
      enabled: true
      # 请求前缀
      pathMapping: /
    knife4j:
      enable: true
      basic:
        #设置密码
        enable: true
        username: admin
        password: admin
      setting:
        language: zh-CN
    

    SwaggerConfig.java

    @Configuration
    @EnableKnife4j
    @EnableOpenApi
    public class SwaggerConfig {
    
    
        /**
         * 是否开启swagger
         */
        @Value("${swagger.enabled}")
        private boolean enabled;
    
        /**
         * 设置请求的统一前缀
         */
        @Value("${swagger.pathMapping}")
        private String pathMapping;
    
        @Bean
        public Docket docket() {
            return new Docket(DocumentationType.OAS_30)
                    .apiInfo(apiInfo())
                    .enable(enabled)
                    .select()
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .paths(PathSelectors.any())
                    .build()
                    .pathMapping(pathMapping);
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder().title("标题").description("简介")
                    .termsOfServiceUrl("http://localhost:8080/").version("0.0.1")
                    .contact(new Contact("作者姓名", "", "邮箱")).build();
        }
    }
    

    添加 BeanPostProcessorConfig.java

    参考:https://github.com/springfox/springfox/issues/3462

    参考:https://blog.csdn.net/quanzhan_King/article/details/131409106

    import lombok.extern.slf4j.Slf4j;
    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.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;
     
    @Slf4j
    @Configuration
    public class BeanPostProcessorConfig {
     
        @Bean
        public 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);
                    }
                }
            };
        }
     
    }
    

    页面访问

    相关文章

      网友评论

          本文标题:SpringBoot2.7.6整合Swagger3

          本文链接:https://www.haomeiwen.com/subject/hmpuqjtx.html