Search code examples
javaspring-bootinterceptorresttemplatespring-cloud-netflix

Spring cloud - Resttemplate doesn't get injected in interceptor


I created a resttemplate in my spring boot application like this:

@Configuration
public class MyConfiguration {

@LoadBalanced
@Bean
  RestTemplate restTemplate() {
    return new RestTemplate();
  }
}

This works fine in all classes when autowired. However, in my interceptor, this throws up nullpointer exception.

What could be the reason and how can I configure a loadbalanced (using Ribbon) resttemplate in my interceptor?

Update:

my interceptor:

 public class MyInterceptor implements HandlerInterceptorAdapter {

  @Autowired
  RestTemplate restTemplate;

  public boolean preHandle(HttpServletRequest request,
    HttpServletResponse response, Object handler)
    throws Exception {

    HttpHeaders headers = new HttpHeaders();
    ...
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    //restTemplate is null here
    ResponseEntity<String> result = 
    restTemplate.exchange("<my micro service url using service name>", 
                          HttpMethod.POST, entity, String.class);
    ...

    return true;
}

Interceptor is added to spring boot application like this:

@Configuration  
public class MyConfigAdapter extends WebMvcConfigurerAdapter  {

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

Solution

  • You misunderstand how @Autowired works. As soon as you new MyInterceptor() outside of a @Bean method, it will not get autowired.

    Do something like below:

    @Configuration  
    public class MyConfigAdapter extends WebMvcConfigurerAdapter  {
    
        @Autowired
        MyInterceptor myInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor).addPathPatterns("/*");
        }
    }