Spring Boot应用程序中注入的Spring Bean为NULL

时间:2017-09-27 04:33:15

标签: java spring spring-boot dependency-injection autowired

我使用Spring Boot(1.5.3)开发REST Web服务。为了对传入请求采取某些操作,我添加了一个拦截器,如下所示。

@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有一个自动装配的Spring Bean 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/**");
}
} 

我的Spring Boot应用程序

@SpringBootApplication
public class SpringBootApp {

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

}
}

现在,当请求进入时,它会以preHandle RequestInterceptor方法登陆,但RequestParser为NULL。如果我从@Component中删除RequestParser注释,则在Spring上下文初始化No bean found of type RequestParser期间出现错误。这意味着RequestParser在Spring上下文中注册为Spring bean,但为什么它在注入时为NULL?有什么建议?

1 个答案:

答案 0 :(得分:1)

你的问题在于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/**");
  }
}