代码之家  ›  专栏  ›  技术社区  ›  Meena Chaudhary

注入的Spring Bean在Spring引导应用程序中为空

  •  2
  • Meena Chaudhary  · 技术社区  · 7 年前

    @Component
    public class RequestInterceptor extends HandlerInterceptorAdapter {
    
    @Autowired
    RequestParser requestParser;
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    
        //HandlerMethod handlerMethod = (HandlerMethod) handler;
        requestParser.parse(request);
        return true;
    }
    }
    

    RequestInterceptor RequestParser 负责解析请求。

    @Component
    public class RequestParserDefault implements RequestParser {
    
    @Override
    public void parse(HttpServletRequest request) {
    
        System.out.println("Parsing incomeing request");
    }
    
    }
    

    拦截器注册

    @Configuration  
    public class WebMvcConfig extends WebMvcConfigurerAdapter  {  
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/usermanagement/v1/**");
    }
    } 
    

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

    现在,当一个请求进来时,它就会登陆 preHandle 方法 但是 为空。如果我删除 @Component 注释自 请求解析器 我在Spring上下文初始化期间出错 No bean found of type RequestParser 请求解析器 在Spring上下文中注册为Spring bean,但为什么在注入时为NULL?有什么建议吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Florian Fray    7 年前

    new RequestInterceptor() . 重写WebMvcConfig以注入它,例如:

    @Configuration  
    public class WebMvcConfig extends WebMvcConfigurerAdapter  {  
    
      @Autowired
      private RequestInterceptor requestInterceptor;
    
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestInterceptor)
                .addPathPatterns("/usermanagement/v1/**");
      }
    }