Spring cloud - Resttemplate doesn't get injected in interceptor

假如想象 提交于 2019-12-08 09:39:18

问题


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

回答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("/*");
    }
}


来源:https://stackoverflow.com/questions/43243402/spring-cloud-resttemplate-doesnt-get-injected-in-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!