Spring cloud - Resttemplate 没有被注入拦截器

Spring cloud - Resttemplate doesn't get injected in interceptor

我在 spring 引导应用程序中创建了一个 resttemplate,如下所示:

@Configuration
public class MyConfiguration {

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

这在所有 类 自动装配时工作正常。但是,在我的拦截器中,这会引发空指针异常。

可能是什么原因以及如何在我的拦截器中配置负载平衡(使用功能区)resttemplate?

更新:

我的拦截器:

 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;
}

拦截器被添加到 spring 引导应用程序,如下所示:

@Configuration  
public class MyConfigAdapter extends WebMvcConfigurerAdapter  {

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

您误解了 @Autowired 的工作原理。一旦您 new MyInterceptor()@Bean 方法之外,它就不会自动装配。

执行如下操作:

@Configuration  
public class MyConfigAdapter extends WebMvcConfigurerAdapter  {

    @Autowired
    MyInterceptor myInterceptor;

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