SpringBoot高版本添加拦截器,替代WebMvcConfigurerAdapter

一.创建类实现HandlerInterceptor接口,重写接口中的三个方法

@Component注解,方便后面使用时进行注入

@Slf4j注解,简化log写法,添加lombok依赖后可以使用

package com.datang.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class InterceptorConfig implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception{
        log.info("自定义拦截器");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView modelAndView){
        log.info("处理请求完成后视图渲染之前的处理操作");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception {
        log.info("视图渲染之后的操作");
    }

}

二.spring boot 2.0、Spring 5.0 以后WebMvcConfigurerAdapter会取消掉,新的版本解决方案目前有两种:

1) 创建类继承WebMvcConfigurationSupport类,覆盖其addInterceptors接口并注册我们自己的拦截器

@SpringBootConfiguration注解表明这是一个配置类

package com.datang.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@SpringBootConfiguration
public class WebAppConfig extends WebMvcConfigurationSupport {

    @Autowired
    InterceptorConfig interceptorConfig;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册自定义拦截器,添加拦截路径和排除拦截路径
        registry.addInterceptor(interceptorConfig).addPathPatterns("/**").excludePathPatterns("/logger/**");
    }
}

2)直接实现WebMvcConfigurer

package com.datang.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootConfiguration
public class WebAppConfig implements WebMvcConfigurer {

    @Autowired
    InterceptorConfig interceptorConfig;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册自定义拦截器,添加拦截路径和排除拦截路径
        registry.addInterceptor(interceptorConfig).addPathPatterns("/**").excludePathPatterns("/logger/**");
    }
}

运行结果如下: SpringBoot高版本添加拦截器,替代WebMvcConfigurerAdapter