SpringBoot拦截器或SpringMVC拦截器,@Autowired自动注入为null问题

最近使用SpringBoot的自定义拦截器,在拦截器中注入了一个RedisService,准备下面作相应操作,拦截器代码:

public class WebAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
     
    }
    
    ...
}

配置信息代码:

@Configuration
public class WebAdminInterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WebAdminInterceptor()).addPathPatterns("/**").excludePathPatterns("/static");
    }
}

看起来没有问题,但debug发现拦截器中注入的redisService为null。

原因

个人觉得可能是这个拦截应该先托管给spring容器进行实例化,然后在添加拦截器的时候获取这个bean,不能直接new吧,new的话没有控制反转,也就是没有交给spring容器管理,自然里面的@Autowired没有效果

解决

解决方法就是让bean交给Spring容器实例化,将配置信息修改为如下:

@Configuration
public class WebAdminInterceptorConfig implements WebMvcConfigurer {

    @Bean
    WebAdminInterceptor webAdminInterceptor(){
        return new WebAdminInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(webAdminInterceptor()).addPathPatterns("/**").excludePathPatterns("/static");
    }
}

重新运行即可注入成功。

发布了27 篇原创文章 · 获赞 32 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39809458/article/details/99829440