简体   繁体   中英

Injected Spring Bean is NULL in Spring Boot Application

I am using Spring Boot(1.5.3) to develop a REST Web Service. In order to take some action on incoming request I have added an interceptor shown below.

@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 has an autowired Spring Bean RequestParser responsible for parsing the request.

@Component
public class RequestParserDefault implements RequestParser {

@Override
public void parse(HttpServletRequest request) {

    System.out.println("Parsing incomeing request");
}

}

Interceptor registration

@Configuration  
public class WebMvcConfig extends WebMvcConfigurerAdapter  {  

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

And my Spring Boot Application

@SpringBootApplication
public class SpringBootApp {

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

}
}

Now when a request comes in, it lands in preHandle method of RequestInterceptor but RequestParser is NULL. If I remove the @Component annotation from RequestParser I get an error during Spring context initialization No bean found of type RequestParser . That means RequestParser is registered as Spring bean in Spring context but why it is NULL at the time of injection? Any suggestions?

Your problem lies in this new RequestInterceptor() . Rewrite your WebMvcConfig to inject it, eg like this:

@Configuration  
public class WebMvcConfig extends WebMvcConfigurerAdapter  {  

  @Autowired
  private RequestInterceptor requestInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(requestInterceptor)
            .addPathPatterns("/usermanagement/v1/**");
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM