一种通过在你自定义的拦截类上注入@Component,然后引用拦截类
另外一个就是new Object,并且加上@Bean
方式一:@Bean
拦截器只需要两步:一、实现HandlerInterceptor 接口 然后引用
自定义了我的拦截类—implements
public class MyInterceptor implements HandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);
@Autowired
private RedisToken rtm;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//业务逻辑
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
1.2 在@Configuration这个文件下使用
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 将自定义拦截器作为Bean写入配置
* @return
*/
@Bean
public MyInterceptor getMyInterceptor() {
return new MyInterceptor();
}
/**
* 对拦截器注册
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("拦截器");
registry.addInterceptor(getMyInterceptor()) //这里放你@Bean的那个方法
.addPathPatterns("/**")
.excludePathPatterns("/login/userlogin")
.excludePathPatterns("/login/interceptor");
}
}
在前面代码的基础上改动 方式不一样
方式二:拦截类使用@Component注入
2.1 自定义拦截类上加@Component
@Component
public class MyInterceptor implements HandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);
@Autowired
private RedisToken rtm;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//业务逻辑
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
2.2@Configuration里面使用
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//使用@Autowired 从spring中拿到之前@Component注入的拦截器对象
@Autowired
public MyInterceptor myInterceptor;
/**
* 对拦截器注册
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("拦截器");
registry.addInterceptor(myInterceptor) //这里放@Autowired拿到的对象
.addPathPatterns("/**")
.excludePathPatterns("/login/userlogin")
.excludePathPatterns("/login/interceptor");
}
}
其中一种测试一下 发送的请求进入到了拦截器里面 成功!!!