Spring Boot 2.5.x 整合 swagger 3.0

1. 依赖版本

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.18</version>
        </dependency>
        <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>

2. Spring Boot 2.5.x ~ 2.7.18

2.1 swagger配置属性

@ConfigurationProperties("swagger")
public class SwaggerProperties {
    /**
     * 是否开启swagger
     */
    private Boolean enabled = true;
    /**
     * 标题
     **/
    private String title = "API文档";
    /**
     * 描述
     **/
    private String desc = "";
    /**
     * 版本
     **/
    private String version = "v3.0";
    /**
     * 许可证
     **/
    private String license = "Powered By Swagger";
    /**
     * 许可证URL
     **/
    private String licenseUrl = "https://swagger.io/";
    /**
     * 服务条款URL
     **/
    private String termsOfServiceUrl = "";
    /**
     * host信息
     **/
    private String host = "";
    /**
     * 接口前缀
     */
    private String pathMapping = "";
    /**
     * 排除路径
     */
    private List<String> excludePaths = new ArrayList<>();
    /**
     * 联系人信息
     */
    private Contact contact = new Contact();
    
    public static class Contact {
        /**
         * 联系人
         **/
        private String name = "";
        /**
         * 联系人url
         **/
        private String url = "";
        /**
         * 联系人email
         **/
        private String email = "";
    }
}

2.2 swagger配置

@Component
public class SwaggerWebConfiguration implements WebMvcConfigurer {
    private static final Logger log = LoggerFactory.getLogger(SwaggerWebConfiguration.class);

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** swagger-ui 地址 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").
                addResourceLocations("classpath:/META-INF/resources/webjars/");
        log.info("映射swagger资源路径");
    }
}

解决 springboot 2.5.x 默认使用 path-pattern-matcher,swagger扫描不到接口

@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfiguration implements ApplicationListener<WebServerInitializedEvent> {
    private static final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);

    private final WebMvcProperties webMvcProperties;

    public SwaggerConfiguration(WebMvcProperties webMvcProperties) {
        this.webMvcProperties = webMvcProperties;
    }

    @Bean
    public Docket api(SwaggerProperties swaggerProperties) {
        webMvcProperties.getPathmatch().setMatchingStrategy(WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER);
        ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.OAS_30)
                .enable(swaggerProperties.getEnabled())
                .host(swaggerProperties.getHost())
                .pathMapping(swaggerProperties.getPathMapping())
                .apiInfo(apiInfo(swaggerProperties)).select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(PutMapping.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(PostMapping.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(DeleteMapping.class))
                .paths(PathSelectors.any())
                .paths(PathSelectors.regex("/.*/error").negate());
        swaggerProperties.getExcludePaths().forEach(path -> apiSelectorBuilder.paths(PathSelectors.ant(path).negate()));
        return apiSelectorBuilder.build()
                .protocols(new HashSet<String>() {{
                    add("https");
                    add("http");
                }})
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }
    
    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey(HeaderConstant.TOKEN, HeaderConstant.TOKEN, io.swagger.v3.oas.models.security.SecurityScheme.In.HEADER.toString()));
        return apiKeyList;
    }
    
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(SecurityContext.builder().securityReferences(Collections.singletonList(new SecurityReference(HeaderConstant.TOKEN, new AuthorizationScope[]{new AuthorizationScope("global", "token授权信息")}))).operationSelector(o -> o.requestMappingPattern().matches("/.*")).build());
        return securityContexts;
    }

    private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDesc())
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
                .version(swaggerProperties.getVersion())
                .build();
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        try {
            SwaggerProperties swaggerProperties = event.getApplicationContext().getBean(SwaggerProperties.class);
            if (swaggerProperties.getEnabled()) {
                String hostAddress = Inet4Address.getLocalHost().getHostAddress();
                int port = event.getWebServer().getPort();
                String contextPath = event.getApplicationContext().getApplicationName();
                System.out.println(
                        " __            __   __   __  __  \n" +
                                "(_  |  |  /\\  / _  / _  |_  |__) \n" +
                                "__) |/\\| /--\\ \\__) \\__) |__ |  |"
                );
                System.out.println(String.format("http://%s:%s%s/doc.html", hostAddress, port, contextPath));
                System.out.println(String.format("http://%s:%s%s/swagger-ui/index.html", hostAddress, port, contextPath));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

swagger 在 springboot 2.5.x 不兼容问题

@Component
public class SwaggerBeanPostProcessor implements BeanPostProcessor {
    private static final Logger log = LoggerFactory.getLogger(SwaggerBeanPostProcessor.class);

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
            customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
            log.info("处理swagger在springboot2.6.x不兼容的问题");
        }
        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);
            List<RequestMappingInfoHandlerMapping> requestMappingInfoHandlerMappings = (List<RequestMappingInfoHandlerMapping>) field.get(bean);
            return requestMappingInfoHandlerMappings;
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }
}

3. 备注

这段代码

webMvcProperties.getPathmatch().setMatchingStrategy(WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER);

也可以写在yaml中

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
# swagger:
  # title: 数据处理
  # pathMapping: /data
  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!要将Spring Boot 2.6与Swagger 3.0整合在一起,你可以按照以下步骤进行操作: 步骤1:添加Swagger依赖 在你的Spring Boot项目的pom.xml文件中,添加Swagger的依赖: ```xml <dependencies> <!-- 其他依赖 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> </dependencies> ``` 步骤2:配置Swagger 创建一个Swagger配置类,用于配置Swagger的相关信息: ```java import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; @Configuration @EnableSwagger2 public class SwaggerConfig { public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API 文档") .description("API 文档") .version("1.0.0") .build(); } } ``` 步骤3:启用Swagger 在你的Spring Boot应用程序的主类上使用`@EnableSwagger2`注解来启用Swagger: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @SpringBootApplication @Import(SwaggerConfig.class) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 步骤4:访问Swagger UI 在启动你的应用程序后,你可以通过访问`http://localhost:8080/swagger-ui/`来查看生成的API文档。 以上就是将Spring Boot 2.6与Swagger 3.0整合的基本步骤。你可以根据自己的需要进一步定制和配置Swagger。希望能对你有所帮助!如果有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值