SpringBoot官方文档中的说明:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc . If you wish to provide custom instances of RequestMappingHandlerMapping , RequestMappingHandlerAdapter , or ExceptionHandlerExceptionResolver , you can declare a WebMvcRegistrationsAdapter instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc .
翻译:
如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现 WebMvcConfigurer ,并且添加 @Configuration 注 解,但是千万不要加 @EnableWebMvc 注解。如果你想要自定义 HandlerMapping 、 HandlerAdapter 、 ExceptionResolver 等组件,你可以创建一个 WebMvcRegistrationsAdapter 实例来提供以上组件。如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加 @Configuration 注解和 @EnableWebMvc 注解
需求:在springboot项目中实现自定义springmvc拦截器
1)编写拦截器
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.debug("MyInterceptor的preHandle方法");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.debug("MyInterceptor的postHandle方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.debug("MyInterceptor的afterCompletion方法");
}
}
在application.yml中可以设置日志记录级别
#设置日志记录级别
logging:
level:
com.sx: debug
org.springframework: info
2)编写配置类实现 WebMvcConfigurer,在该类中添加各种组件
@Configuration
public class MvcConfig implements WebMvcConfigurer {
//注册拦截器
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
//添加拦截器到springmvc拦截器链
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
}
}
3)测试
运行项目在控制台可以看见如下输出