spring boot的静态资源不能访问

  • 2019-03-22
  • 浏览 (332)

在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源(classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不能访问。查看 WebMvcAutoConfiguration 的源码:
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
        WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
        ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

    public static String DEFAULT_PREFIX = "";

    public static String DEFAULT_SUFFIX = "";
...
这是因为在 springboot的web自动配置类 WebMvcAutoConfiguration 上有条件注解
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
这个注解的意思是在项目类路径中缺少 WebMvcConfigurationSupport 类型的bean时改自动配置类才会生效,所以继承 WebMvcConfigurationSupport 后需要自己再重写相应的方法。可以在 WebMvcConfigurationSupport 添加如下代码,即可支持访问 swagger 生成的api文档:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
     registry.addResourceHandler("swagger-ui.html")
             .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
     registry.addResourceHandler("/webjars/**")
             .addResourceLocations("classpath:/META-INF/resources/webjars/");
     super.addResourceHandlers(registry);
}


正文到此结束