攔截器不是一個普通屬性,而是一個類,所以就要用到java配置方式了。在SpringBoot官方文檔中有這麼一段說明:
- 如果你想要保持Spring Boot 的一些默認MVC特徵,同時又想自定義一些MVC配置(包括:攔截器,格式化器, 視圖控制器、消息轉換器 等等),你應該讓一個類實現WebMvcConfigurer,並且添加@Configuration註解。如果你想要自定義HandlerMapping、HandlerAdapter、ExceptionResolver等組件,你可以創建一個WebMvcRegistrationsAdapter實例 來提供以上組件。
總結:通過實現WebMvcConfigurer並添加@Configuration註解來實現自定義部分SpringMvc配置。
實現如下:
1、MyInterceptor-定義一個攔截器
@Component
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!");
}
}
@Component
- 在WebMvcConfiguration實現類中用到了@Autowired註解,被註解的這個類是從Spring容器中取出來的,那調用的這個類也需要被Spring容器管理,加上@Component把普通pojo實例化到spring容器中
2、WebMvcConfiguration-定義配置類,註冊攔截器
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
@Autowired
private HandlerInterceptor myInterceptor;
/**
* 重寫接口中的addInterceptors方法,添加自定義攔截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}