0

我创造这样在我的春天启动应用程序resttemplate:春季云 - Resttemplate没有得到注入拦截

@Configuration 
public class MyConfiguration { 

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

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

可能是什么原因以及如何在拦截器中配置loadbalanced(使用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; 
} 

拦截器被添加到春季启动应用程序是这样的:

@Configuration 
public class MyConfigAdapter extends WebMvcConfigurerAdapter { 

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

请出示更多关于你的拦截器。没有足够的信息来回答。 – spencergibb

+0

@spencergibb,添加了我的代码。我可以确认它工作正常,如果我在拦截器中创建新的RestTemplate(未负载均衡)并使用“我的微服务url和端口号”而不是服务名称。 – Jayz

回答

0

你误解如何@Autowired作品。 @Bean方法之外,只要您new MyInterceptor()不会自动布线。

做类似如下:

@Configuration 
public class MyConfigAdapter extends WebMvcConfigurerAdapter { 

    @Autowired 
    MyInterceptor myInterceptor; 

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

绝对正确。这让我的眼睛略微看到了春天的作品。必须将@Component添加到我的拦截器以使自动装配工作。 – Jayz

+0

介意接受答案? – spencergibb