用 心 生 活 , 用 心 爱 你 😘|

Hello霖

园龄:4年1个月粉丝:4关注:0

springboot 登录校验拦截器HandlerInterceptor注入失败为null问题

拦截器校验token 使用到了redis

注入的时候用了@Autowired  

 

  @Autowired
    private StringRedisTemplate redis;

 

发现注入一直为null 报错无法使用

原因是  拦截器是在springcontext之前就创建的,redis还未被加载出来,所以注入直接为空

 

需要修改WebMvcConfigurer配置

 

旧代码:

复制代码
@Configuration
public class MVCconfiguration implements WebMvcConfigurer {

//token校验拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login","/user/verify","/user/register","/user/regCode","/alipaynotify");

    }


}
复制代码

 

 

 

修改后代码如下:

复制代码
@Configuration
public class MVCconfiguration implements WebMvcConfigurer {

    @Bean
    LoginInterceptor getinInterceptor(){
        return new LoginInterceptor();
    }

//token校验拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getinInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login","/user/verify","/user/register","/user/regCode","/alipaynotify");

    }


}
复制代码

 

新建一个@Bean 方法   让Spring管理

现在通过@Bean的方式来创建这个拦截器对象,把创建对象的主动权交给了spring,然后拦截器那边就可以正常注入了,

其实不单单在这里会出现这个情况,只要是你自己new出来的对象,

然后这个对象里面的内容你去@Autowired都会为null,因为你自己new对象了 spring就不会管理这个对象了,那么里面的注入的对象肯定也必须你自己去创建才行啦 

 

本文作者:Hello霖

本文链接:https://www.cnblogs.com/Hello233/p/16030620.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Hello霖  阅读(899)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起