首先,在pom.xml中引入spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
然后,SpringBootMVC中提供了一些静态资源的目录,在src\main\resources下,分别为public,static,resources,META-INF/resources,优先级依次从低到高。只要将静态资源放入上述文件夹(folder)中,即可访问。
其次,如果想要自定义文件夹作为自定义的静态资源目录,只需要编写个类实现WebMvcConfigurer接口,重写addResourceHandlers方法,并将自定义的配置类扫描进组件即可
@Component
public class MyResourceConfiguration implements WebMvcConfigurer{
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/**")
.addResourceLocations(
"classpath:/mystatic/",
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/");
}
}