在拦截器中注入redisTemplate出现空指针是因为拦截器是最先执行的,还未初始化bean,所以要在拦截器执行前将注入bean
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
}
这种情况下ValueOperations<String, Object> operations = redisTemplate.opsForValue();会出现空指针
解决方式两种方式:
第一种方式:创建RedisUtil公共类
自定义一个RedisUtil
@Component//项目运行时就注入Spring容器
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
//赋值一个静态的redis
public static RedisTemplate redis;
@PostConstruct //此注解表示构造时赋值
public void redisTemplate() {
redis = this.redisTemplate;
}
}
在拦截器中不用注入
@Autowired
private RedisTemplate redisTemplate;
直接调用RedisUtil中的静态方法
ValueOperations<String, Object> operations = RedisUtil.redis.opsForValue();
第二种方式:在拦截器执行前将注入bean
/**
* 此模块块儿为拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
}
@Configuration
public class MyWebConfigurer extends WebMvcConfigurerAdapter {
/**
* 注入bean
* @return
*/
@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(loginInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
这种情况下就能在项目启动的时候执行MyWebConfigurer的时候注入自己的LoginInterceptor,实现项目启动的时候RedisTemplate的注入