解决Interceptor的RedisTemplate注入
需求,前台登录后才能访问后端的其他接口
***问题***后端使用了Interceptor进行拦截,前端将token存入cookie,带给后端token,后端查询redis对比token,结果redisTemplate为null;
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Autowired
private StringRedisTemplate redisTemplate;
}
问题分析,redisTemplate在注入spring容器的时候是在LoginInterceptor注入容器之后,直接注入肯定为空,例如下面这段代码。这是Interceptor的配置类。向spring容器中添加了一个LoginInterceptor;
***解决方法***解决从配置类下手,将Interceptor的实例化滞后,@Bean在Interceptor实例化的时候对redisTemplate也进行了实例化
package org.pollution.pollutionproject.mvc.interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyAdapter extends WebMvcConfigurationSupport {
@Bean
public LoginInterceptor getLoginInterceptor(){
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(getLoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/do/login");
// 添加注册器
super.addInterceptors(registry);
}
}
***结果***这样Interceptor成功注入了redisTemplate实例;