Spring Boot 静态资源配置

1、默认配置

Spring Boot 默认采用 WebMvcAutoConfiguration 类中配置的默认属性,但在项目开发过程当中,默认配置可能没法知足实际需求。css

默认状况下spring boot 将 /** 映射到 classpath 中如下路径:html

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources

默认状况下,将静态资源直接放在以上四个路径下,能够直接进行访问,如:spring

/static/index1.html
/public/index2.html
/resources/index3.html

分别执行请求:mvc

http://localhost:8080/index1.html
http://localhost:8080/index2.html
http://localhost:8080/index3.html

则分别返回index1.html、index2.html 、index3.html内容,说明spring boot 会在以上文件夹中查找对应资源并返回。app

配置自定义路径

spring boot 默认设置了4个文件路径用于存放静态资源,可是在实际开发中会对静态资源进行分组管理,对于这种状况,spring boot 默认是没法访问到的,如:ide

/static/css/style.css
/static/js/main.js
/static/img/icon.png

分别请求以上四个文件,会返回404。缘由在于spring boot 默认只在/static /resources /public /META-INF/resources四个路径中进行查找,并不包含子路径。spa

方式一(推荐):配置静态资源类,继承 WebMvcConfigurerAdapter

如将全部/static/**静态资源访问都映射到classpath:/static/路径下:code

/**
 * Author: yxguang.<br>  
 * Email: yxguang1988@gmail.com<br>
 * Description: 静态资源配置<br>
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

方式二:静态配置文件application.properties配置

# spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.static-path-pattern=/static/**
#spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ # Locations of static resources.

这个配置会影响默认的/**,例如修改成/static/**后,只能映射如/static/js/main.js这样的请求(修改前是/js/main.js)。这个配置只能写一个值,不像大多数能够配置多个用逗号隔开的。
经过spring.mvc.static-path-pattern这种方式配置,会使Spring Boot的默认配置失效,也就是说,/public /resources 等默认配置不能使用。 配置中配置了静态模式为/static/,就只能经过/static/来访问。htm

相关文章
相关标签/搜索