spring boot项目中的静态资源文件存放在static文件下面,当通过浏览器访问这些静态文件时,发现必须要添加static作为前缀才能访问,折腾了一番后发现,这个前缀跟 spring.mvc.static-path-pattern 这个配置项有关。

spring:
    mvc:
        static-path-pattern: /static/**<br><br>

项目中application.yml配置文件中,存在如上配置项时,访问静态资源文件要加static才行,当把这个配置项除掉时,不用加static作为前缀亦可进行正常访问。

图片描述

当spring boot自动装配 org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,当执行到org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#addResourceHandlers方法时,类org.springframework.boot.autoconfigure.web.WebMvcProperties#staticPathPattern的默认值为 "/**"。如果配置项文件中存在spring.mvc.static-path-pattern 配置项,默认的配置项将会被覆盖。

图片描述

当通过浏览器进行访问时,springMVC使用SimpleUrlHandlerMapping进行路由映射,当执行到方法 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#lookupHandler 时,将会使用 spring.mvc.static-path-pattern 配置项来匹配url

图片描述