0

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("/*");
    }
}
Jayz
  • 1,174
  • 2
  • 19
  • 43
  • Please show more about your interceptor. There's not enough information to answer. – spencergibb Apr 06 '17 at 00:33
  • @spencergibb, added my code. I can confirm it works fine if I create a new RestTemplate (not loadbalanced) in my interceptor and use "my microservice url and port number" instead of service name. – Jayz Apr 06 '17 at 01:42

1 Answers1

1

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("/*");
    }
}
spencergibb
  • 24,471
  • 6
  • 69
  • 75
  • absolutely right. That opened my eyes a little on how spring works. Had to add @Component to my interceptor to make autowiring work. – Jayz Apr 06 '17 at 02:23