SpringBoot拦截器怎么配置?手把手教你实现自定义拦截器
SpringBoot添加拦截器
拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢?
拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。
在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注解
首先我们定义一个拦截器
@Component
//继承HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle method is running!");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle method is running!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion method is running!");
}
}
定义配置类,注册拦截器
@Configuration
//实现`WebMvcConfigurer`,并且添加`@Configuration`注解
public class MvcConfiguration implements WebMvcConfigurer {
//注入定义的拦截器
@Autowired
private HandlerInterceptor myInterceptor;
/**
* 重写接口中的addInterceptors方法,添加自定义拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
/*拦截路径*/ registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
接下来运行并查看日志
preHandle method is running!
postHandle method is running!
afterCompletion method is running!
你会发现日志中只有这些打印信息,springMVC的日志信息都没有,因为springMVC记录的log级别是debug,springboot默认是显示info以上,我们需要进行配置。
SpringBoot通过logging.level.*=debug来配置日志级别,*填写包名
# 设置org.springframework包的日志级别为debug logging.level.org.springframework=debug
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot整合Netty+Websocket实现消息推送的示例代码
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,本文主要介绍了SpringBoot整合Netty+Websocket实现消息推送的示例代码,具有一定的参考价值,感兴趣的可以了解一下2024-01-01
SpringBoot使用编程方式配置DataSource的方法
这篇文章主要介绍了SpringBoot使用编程方式配置DataSource的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-01-01


最新评论