
4.2 静态资源访问
在Spring MVC中,对于静态资源都需要开发者手动配置静态资源过滤。Spring Boot中对此也提供了自动化配置,可以简化静态资源过滤配置。
4.2.1 默认策略
Spring Boot中对于Spring MVC的自动化配置都在WebMvcAutoConfiguration类中,因此对于默认的静态资源过滤策略可以从这个类中一窥究竟。
在WebMvcAutoConfiguration类中有一个静态内部类WebMvcAutoConfigurationAdapter,实现了4.1节提到的WebMvcConfigurer接口。WebMvcConfigurer接口中有一个方法addResourceHandlers,是用来配置静态资源过滤的。方法在WebMvcAutoConfigurationAdapter类中得到了实现,部分核心代码如下:

Spring Boot在这里进行了默认的静态资源过滤配置,其中staticPathPattern默认定义在WebMvcProperties中,定义内容如下:

this.resourceProperties.getStaticLocations()获取到的默认静态资源位置定义在ResourceProperties中,代码如下:

在getResourceLocations方法中,对这4个静态资源位置做了扩充,代码如下:

其中,SERVLET_LOCATIONS的定义是一个{ "/" }。
综上可以看到,Spring Boot默认会过滤所有的静态资源,而静态资源的位置一共有5个,分别是"classpath:/META-INF/resources/"、"classpath:/resources/"、"classpath:/static/"、"classpath:/public/"以及"/",也就是说,开发者可以将静态资源放到这5个位置中的任意一个。注意,按照定义的顺序,5个静态资源位置的优先级依次降低。但是一般情况下,Spring Boot项目不需要webapp目录,所以第5个"/"可以暂不考虑。
在一个新创建的Spring Boot项目中,添加了spring-boot-starter-web依赖之后,在resources目录下分别创建4个目录,4个目录中放入同名的静态资源(如图4-4所示,数字表示不同位置资源的优先级)。

图4-4
此时,在浏览器中输入“http://localhost:8080/p1.png”即可看到classpath:/META-INF/resources/目录下的p1.png,如果将classpath:/META-INF/resources/目录下的p1.png删除,就会访问到classpath:/resources/目录下的p1.png,以此类推。
如果开发者使用IntelliJ IDEA创建Spring Boot项目,就会默认创建出classpath:/static/目录,静态资源一般放在这个目录下即可。
4.2.2 自定义策略
如果默认的静态资源过滤策略不能满足开发需求,也可以自定义静态资源过滤策略,自定义静态资源过滤策略有以下两种方式:
1. 在配置文件中定义
可以在application.properties中直接定义过滤规则和静态资源位置,代码如下:

过滤规则为/static/**,静态资源位置为classpath:/static/。
重新启动项目,在浏览器中输入“http://localhost:8080/static/p1.png”,即可看到classpath:/static/目录下的资源。
2. Java编码定义
也可以通过Java编码方式来定义,此时只需要实现WebMvcConfigurer接口即可,然后实现该接口的addResourceHandlers方法,代码如下:

重新启动项目,在浏览器中输入“http://localhost:8080/static/p1.png”,即可看到classpath:/static/目录下的资源。