一尘不染

Spring Cloud-RestTemplate不会注入拦截器

spring-boot

我在Spring Boot应用程序中创建了一个resttemplate,如下所示:

@Configuration
public class MyConfiguration {

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

自动接线时,在所有类中都可以正常工作。但是,在我的拦截器中,这引发了nullpointer异常。

原因可能是什么?如何在拦截器中配置负载平衡(使用功能区)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 Boot应用程序中:

@Configuration  
public class MyConfigAdapter extends WebMvcConfigurerAdapter  {

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

阅读 558

收藏
2020-05-30

共1个答案

一尘不染

您误会了@Autowired工作原理。一旦您new MyInterceptor()处于@Bean方法之外,它就不会自动连接。

执行以下操作:

@Configuration  
public class MyConfigAdapter extends WebMvcConfigurerAdapter  {

    @Autowired
    MyInterceptor myInterceptor;

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