【问题标题】:Spring cloud - Resttemplate doesn't get injected in interceptorSpring cloud - Resttemplate 没有被注入拦截器
【发布时间】:2017-04-05 23:47:47
【问题描述】:

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

@Configuration
public class MyConfiguration {

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

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

可能是什么原因以及如何在我的拦截器中配置负载平衡(使用 Ribbon)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("/*");
    }
}

【问题讨论】:

  • 请展示更多关于你的拦截器的信息。没有足够的信息来回答。
  • @spencergibb,添加了我的代码。如果我在拦截器中创建一个新的 RestTemplate(未负载平衡)并使用“我的微服务 url 和端口号”而不是服务名称,我可以确认它工作正常。

标签: java spring-boot interceptor resttemplate spring-cloud-netflix


【解决方案1】:

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

执行以下操作:

@Configuration  
public class MyConfigAdapter extends WebMvcConfigurerAdapter  {

    @Autowired
    MyInterceptor myInterceptor;

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

【讨论】:

  • 绝对正确。这让我对春天的工作原理有了一点了解。必须将 @Component 添加到我的拦截器中才能使自动装配工作。
猜你喜欢
  • 1970-01-01
  • 2019-12-22
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 1970-01-01
  • 2020-05-23
相关资源
最近更新 更多