Spring Boot拦截器里注入对象失败问题解决

一、问题场景:

1、拦截器需要实现HandlerInterceptor接口;

2、使用WebMvcConfigurer接口用来注册拦截器;

3、拦截器中无法自动注入spring bean,使用@Autowired注解或者是构造器注入的对象是null

二、解决方案:

使用WebApplicationContextUtils类来直接获取bean。

Demo demo = org.springframework.web.context.support.WebApplicationContextUtils
          .getRequiredWebApplicationContext(request.getServletContext())
          .getBean(Demo.class);

ok。

原文地址:https://www.cnblogs.com/kjgym/p/11881672.html