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就不会管理这个对象了,那么里面的注入的对象肯定也必须你自己去创建才行啦 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM