spring boot繼承swaggers:swagger-ui No mapping found for HTTP request

一、前言

spring boot 集成swagger 報swagger-ui No mapping found for HTTP request。

二、檢查三點

1、是否引入jar包

  <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>2.6.1</version>
    </dependency>

二、啓動類上加了註解

需要添加@EnableSwagger2 註解

@Configuration
    @EnableSwagger2
    @EnableWebMvc

三、重寫WebMvcConfigurer

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");    
   }
}

四、爲什麼我沒有重寫WebMvcConfigurer 也可以訪問

查看你有沒引入 autoconfigure這個jar包
在這裏插入圖片描述
如果引入,我們知道這個是包是 自動配置的核心jar
查看jar包下這個類:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
在這裏插入圖片描述

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }

這個類的方法自動幫我們配置了,所以不需要手動再重寫WebMvcConfigurer接口 的方法

參考:
https://stackoverflow.com/questions/43545540/swagger-ui-no-mapping-found-for-http-request

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章