现象:
如下配置静态资源拦截,运行时,访问不到static 目录下的静态资源。
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { System.out.println("addResourceHandlers======="); registry.addResourceHandler("/static/**") .addResourceLocations("/static/"); }
原因:
@EnableWebMvc class WebConfig extends WebMvcConfigurationSupport
继承了 WebMvcConfigurationSupport 类,导致 addResourceHandlers 方法的配置完全没有起作用。
因为@EnableWebMvc 会自动导入DelegatingWebMvcConfiguration,会重写addResourceHandlers() 方法。
@Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {}
@EnableWebMvc 的源码
* <p><strong>Note:</strong> only one {@code @Configuration} class may have the * {@code @EnableWebMvc} annotation to import the Spring Web MVC * configuration. There can however be multiple {@code @Configuration} classes * implementing {@code WebMvcConfigurer} in order to customize the provided * configuration. 只有一个类可以加@EnableWebMvc注解,导入spring web mvc 的配置。但是可以由多个类实现接口WebMvcConfigurer 去提供自定义配置。 * * <p>If {@link WebMvcConfigurer} does not expose some more advanced setting that * needs to be configured consider removing the {@code @EnableWebMvc} * annotation and extending directly from {@link WebMvcConfigurationSupport} * or {@link DelegatingWebMvcConfiguration}, e.g.:如果WebMvcConfigurer没有暴露任何配置,可以考虑去掉@EnableWebMvc,直接继承WebMvcConfigurationSupport或DelegatingWebMvcConfiguration。
@Import(DelegatingWebMvcConfiguration.class) public @interface EnableWebMvc { }