springboot拦截器@Autowired Bean为null

springboot自定义拦截器时在debug发现@Autowired下的Bean都为null

问题原因

拦截器加载的时间点在springcontext之前,所以在拦截器中注入自然为null

文件解决

在spring配置文件中这样写

   @Bean
    public HandlerInterceptor getMyInterceptor(){
        return new MyInterceptor();
    }

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

使用bean注解提前加载,即可成功。

猜你喜欢

转载自blog.csdn.net/weixin_39986856/article/details/81150854