为什么你写的拦截器注入不了 Java bean?
一、如何实现拦截器
在Spring Boot项目中,拦截器经常被用来做登陆验证,日志记录等操作。拦截器是Spring提供的,所以可以将拦截器注成bean,由IOC容器来管理。实现拦截器的方式很简单,主要由以下两个步骤:
自定义拦截器类实现HandlerInterceptor接口 自定义WebMvc配置类实现WebMvcConfigurer接口,添加自定义拦截器类
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
if(StringUtils.isEmpty(token)){
...
return false;
}
return true;
}
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
// 拦截的请求
.addPathPatterns("/**")
// 不用拦截的请求
.excludePathPatterns("/login");
}
}
@Component
public class TokenUtil {
/**
* 验证token 是否有效
*/
public boolean checkToken(String token){
...
}
}
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private TokenUtil tokenUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(!tokenUtil.checkToken(token)){
...
return false;
}
return true;
}
}
二、如何将拦截器托管给IOC容器
2.1 在WebConfiguration注入拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor);
}
}
2.2 在WebConfiguration将拦截器注成bean
public class LoginInterceptor implements HandlerInterceptor {
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Bean
public LoginInterceptor loginInterceptor(){
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( loginInterceptor());
}
}
2.3 通过构造器处理
public class LoginInterceptor implements HandlerInterceptor {
private TokenUtil tokenUtil;
public LoginInterceptor(TokenUtil tokenUtil) {
this.tokenUtil = tokenUtil;
}
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Autowired
private TokenUtil tokenUtil;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor(tokenUtil));
}
}
三、总结
评论