springboot 拦截器中使用redis报空指针异常
在 HandlerInterceptor 里使用redis的时候,报空指针异常。
原因:
拦截器的执行是在spring容器中bean初始化之前的,拦截器执行时,spring中我们定义的bean还未初始化,自然也就无法自动注入,无法使用。
解决很简单,在 WebMvcConfigurer 封装 HandlerInterceptor Bean方法,然后 在registry.addInterceptor调用这个Bean方法即可
WebMvcConfigurer
package com.huobiapp.util.interceptor.app;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 东泰 http://dt2008.cn
* 2020-11
*/
@Configuration
public class APPConfig implements WebMvcConfigurer {
// 将拦截器bean化
@Bean
public APPInterceptor loginHandlerInterceptor() {
return new APPInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册TestInterceptor拦截器
InterceptorRegistration registration = registry.addInterceptor(loginHandlerInterceptor());
}
}
HandlerInterceptor
/**
* 用户拦截器
* 东泰 http://dt2008.cn
* 2020-11
*/
public class APPInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
}