实现自定义拦截器 但是不能注入容器的问题

按照网上的说法 添加了一个监听器

@Configuration
public class AuthenticationConfiguration implements WebMvcConfigurer {

      @Autowired
      AuthenticationInterceptor authenticationInterceptor;


      @Override
      public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(authenticationInterceptor);
          WebMvcConfigurer.super.addInterceptors(registry);
      }
}

但是实际测试拦截器中redisUtil注入的还是为null,搞不明白了,哪里还有注解没有加么

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;

启动类


@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


这个问题是因为我写了2个conf 类,都将自定义注解加入了

你需要把 RedisUtil的实例注册到spring,对其增加@Component 之类的注解

可以尝试去掉AuthenticationInterceptor 类上的Component注解,然后通过Bean注解手动注册一下


@Bean
    public AuthenticationInterceptor authenticationInterceptor(){
        return new AuthenticationInterceptor();
    }

这种方式我也尝试过了,还是不行

你写过滤器,不也得写url嘛 不然它哪知道你要拦截哪些url