Spring Cloud-RestTemplate不会注入到拦截器中 [英] Spring cloud - Resttemplate doesn't get injected in interceptor
问题描述
我在Spring Boot应用程序中创建了一个resttemplate,如下所示:
I created a resttemplate in my spring boot application like this:
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
自动接线时,在所有类中都可以正常工作.但是,在我的拦截器中,这引发了nullpointer异常.
This works fine in all classes when autowired. However, in my interceptor, this throws up nullpointer exception.
这可能是什么原因?如何在拦截器中配置负载平衡(使用功能区)resttemplate?
What could be the reason and how can I configure a loadbalanced (using Ribbon) resttemplate in 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;
}
拦截器像这样添加到Spring Boot应用程序中:
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("/*");
}
}
推荐答案
您误解了@Autowired
的工作方式.一旦您new MyInterceptor()
在@Bean
方法之外,它就不会自动连接.
You misunderstand how @Autowired
works. As soon as you new MyInterceptor()
outside of a @Bean
method, it will not get autowired.
执行以下操作:
@Configuration
public class MyConfigAdapter extends WebMvcConfigurerAdapter {
@Autowired
MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/*");
}
}
这篇关于Spring Cloud-RestTemplate不会注入到拦截器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!