弹簧引导应用程序中注入的Spring Bean是NULL

问题描述:

我正在使用Spring Boot(1.5.3)开发REST Web服务。为了对传入的请求采取一些行动,我添加了一个如下所示的拦截器。弹簧引导应用程序中注入的Spring Bean是NULL

@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/**"); 
} 
} 

而且我的春节,引导应用程序

@SpringBootApplication 
public class SpringBootApp { 

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

} 
} 

现在,当一个请求时,它的土地在RequestInterceptorpreHandle方法,但RequestParser为NULL。如果我从RequestParser中删除@Component注释,则在Spring上下文初始化期间出现错误No bean found of type RequestParser。这意味着RequestParser在Spring上下文中被注册为Spring bean,但为什么在注入时它是NULL?有什么建议么?

+0

在RequestParserDefault所在的软件包中可能需要'@ ComponentScan'。 –

+0

@IndraBasak我相信它能够找到并注册bean,因为我在上下文初始化过程中遇到了错误,如果我从中删除了'@ Component'注释。 –

+0

你用'WebMvcConfigurerAdapter'注册了'HandlerInterceptorAdapter'吗? –

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