Spring Boot對映靜態資源
阿新 • • 發佈:2019-02-05
開發配置:
- IntelliJ Idea
- JDK 1.8.0.131 64-bit
- spring boot 1.5.8
1.新建專案
使用Idea新建專案,預設情況下,resource下:META-INF/resources、resources,static、public下的靜態檔案可直接訪問,如下所示:
2.使用@EnableWebMvc並繼承WebMvcConfigurerAdapter類之後,無法訪問靜態資源
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 {
}
解決:
將預設的靜態資源範圍路徑加回來:
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!