SpringBoot攔截器怎么配置?手把手教你實現(xiàn)自定義攔截器
SpringBoot添加攔截器
攔截器也是我們經(jīng)常需要使用的,在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配置(包括:攔截器,格式化器, 視圖控制器、消息轉(zhuǎn)換器 等等),你應該讓一個類實現(xiàn)WebMvcConfigurer,并且添加@Configuration注解,但是千萬不要加@EnableWebMvc注解。
如果你想要自定義HandlerMapping、HandlerAdapter、ExceptionResolver等組件,你可以創(chuàng)建一個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
//實現(xiàn)`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!
你會發(fā)現(xiàn)日志中只有這些打印信息,springMVC的日志信息都沒有,因為springMVC記錄的log級別是debug,springboot默認是顯示info以上,我們需要進行配置。
SpringBoot通過logging.level.*=debug來配置日志級別,*填寫包名
# 設置org.springframework包的日志級別為debug logging.level.org.springframework=debug
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Netty+Websocket實現(xiàn)消息推送的示例代碼
WebSocket使得客戶端和服務器之間的數(shù)據(jù)交換變得更加簡單,允許服務端主動向客戶端推送數(shù)據(jù),本文主要介紹了SpringBoot整合Netty+Websocket實現(xiàn)消息推送的示例代碼,具有一定的參考價值,感興趣的可以了解一下2024-01-01
SpringBoot使用編程方式配置DataSource的方法
這篇文章主要介紹了SpringBoot使用編程方式配置DataSource的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01

