No mapping found for HTTP request with URI [/swagger-ui.html]

今天在使用swagger-ui的是出现一个比较坑的问题,当访问swagger-ui.html的时候会出现
No mapping found for HTTP request with URI [/swagger-ui.html]

解决方法

一、在某个配置类上去掉@EnableWebMvc
二、如果要用@EnableWebMvc,则需要加上如下配置类。

@Configuration
@EnableWebMvc
public class WebMvcConfigurerConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");

        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }
}

深究一下原因
在Spring Boot中使用@EnableWebMvc可能遇到的问题,@EnableWebMvc是使用注解方式快捷配置Spring Webmvc的一个注解。在使用时你可能会遇到以下问题:
⑴ Spring Boot在application文件中的配置失效
⑵ 在Spring Boot的自定义配置类加上@EnableWebMvc后,发现自动配置的静态资源路径(classpath:/META/resources/,classpath:/resources/,classpath:/static/classpath:/public/)资源无法访问。

查看一下@EnableWebMvc源码

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}

可以看到该注解引入了DelegatingWebMvcConfiguration类,再查看一下该类(部分),

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
}

DelegatingWebMvcConfiguration又继承于WebMvcConfigurationSupport。也就是说,如果我们使用@EnableWebMvc就相当于导入了WebMvcConfigurationSupport类,这个时候,Spring Boot的自动装配就不会发生了,我们能用的,只有WebMvcConfigurationSupport提供的若干个配置。其实不使用@EnableWebMvc注解也是可以实现配置Webmvc,只需要将配置类继承于WebMvcConfigurationSupport类即可。
使用@EnableWebMvc时,加载的是WebMvcConfigurationSupport中的配置项。
不使用@EnableWebMvc时,使用的是WebMvcAutoConfiguration引入的配置项。

如果使用@EnableWebMvc了,那么就会自动覆盖了官方给出的/static, /public, META-INF/resources, /resources等存放静态资源的目录。而将静态资源定位于src/main/webapp。当需要重新定义好资源所在目录时,则需要主动添加上述的那个配置类,来重写 addResourceHandlers方法。

@Configuration
@EnableWebMvc
public class MyWebConfig implements WebMvcConfigurer {
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
	   registry.addResourceHandler("/**")
	           .addResourceLocations("classpath:/public/");
	}
}

注意:
Spring Boot 默认提供Spring MVC 自动配置,不需要使用@EnableWebMvc注解