SpringBoot学习笔记(二)—— SpringMvc配置

一、静态资源

以往我们war工程的静态资源都是放在WEB-INF下,而我们现在用SpringBoot构建的是jar工程,那静态资源该放在哪呢。

WebMvcAutoConfiguration类中有一个mvc自动配置的适配器类,它实现了WebMvcConfigurer(提供了各种配置方法)和ResourceLoaderAware(资源加载器) 接口。

    @Configuration
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter
			implements WebMvcConfigurer, ResourceLoaderAware {

我们看@EnableConfigurationProperties启动的配置属性ResourceProperties类:

@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private String[] staticLocations;

可以看到它默认了几种资源路径。一般我们就选择在resources下新建一个static用来存放静态资源。SpringMvc会根据ResourceProperties下staticLocations来找到静态资源。

注:在前后端分离项目中,不需要关注这点。

二、application.yml

可以直接配置端口,拦截路径、日志级别等。

server:
  port: 80
  servlet:
    path: /
logging:
  level: 
    com.orcas.base: debug

三、拦截器

自定义一个拦截器实现HandlerInterceptor接口,重写preHandle()postHandle()afterCompletion()方法。以往可能会在xml中配置拦截器。
现在我们可以创建一个Mvc配置文件实现WebMvcConfigurer接口。
WebMvcConfigurer提供了许多SpringMvc高级配置:
SpringBoot学习笔记(二)—— SpringMvc配置
而且这些方法是用default关键字修饰的,这是在jdk1.8的新特性,我们不需要重写所有方法,根据需求重写即可。
这里我们需要重写的方法是addInterceptors()

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");

    }
}