拦截器加载的时间点在springcontext之前,所以在拦截器中注入自然为null
@Component
public class MyInterceptor implements HandlerInterceptor {
//想要注入的类
@Autowired
UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("request before 拦截");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("post 拦截");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("after 拦截");
}
}
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
//关键,将拦截器作为bean写入配置中
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//多个拦截器组成一个拦截器链
// addPathPatterns用于添加拦截规则
// excludePathPatterns用户排除拦截
registry.addInterceptor(myInterceptor()).addPathPatterns("/**"); //对来自/** 全路径请求进行拦截
super.addInterceptors(registry);
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_43296313/article/details/121423144
内容来源于网络,如有侵权,请联系作者删除!