Spring Boot映射静态资源

开发配置:

  • IntelliJ Idea
  • JDK 1.8.0.131 64-bit
  • spring boot 1.5.8

1.新建项目

使用Idea新建项目,默认情况下,resource下:META-INF/resources、resources,static、public下的静态文件可直接访问,如下所示:

Spring Boot映射静态资源_第1张图片

访问地址:
http://localhost:8080/desert1.jpg
http://localhost:8080/desert2.jpg
http://localhost:8080/desert3.jpg
http://localhost:8080/desert4.jpg

2.使用@EnableWebMvc并继承WebMvcConfigurerAdapter类之后,无法访问静态资源

Spring Boot映射静态资源_第2张图片

WebConfig

package com.example.demo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author Aaron
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {

}

Spring Boot映射静态资源_第3张图片

原因:
@EnableWebMvc配合WebMvcConfigurerAdapter修改了默认的静态资源范围配置,参考:http://blog.csdn.net/pinebud55/article/details/53420481

解决:
将默认的静态资源范围路径加回来:

package com.example.demo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author Aaron
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }

}

再次访问静态资源,ok!

参考:https://stackoverflow.com/questions/24661289/spring-boot-not-serving-static-content


你可能感兴趣的:(spring-boot)