对于restTemplate,Spring Ribbon @LoadBalanced不能与@scope(“prototype”)一起使用

时间:2018-02-21 19:10:43

标签: spring resttemplate netflix-ribbon

我正在关注the official spring ribbon guide,我注意到了一件事。

如果以这种方式创建RestTemplate

@LoadBalanced
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)  ---- I added this line
RestTemplate restTemplate(){
    logger.warn("create a restTemplate bean..."); --- added this for debug
    return new RestTemplate();
}

然后功能区客户端将无法找到服务器。 (无法使用服务器IP地址解析客户端名称);

我调试了bean创建过程,并注意到消息“创建一个restTemplate bean ...”在日志中出现了两次。

自动连线的restTemplate实例没有LoadBalancerInterceptor,这可能就是它失败的原因。

所以我想知道是否有任何建议可以解决这个问题?

P.S:我需要RestTemplate作为原型,以便我可以设置不同的errorHandlers。

2 个答案:

答案 0 :(得分:0)

事实证明@LoadBalanced注释不会从应用程序上下文中检索RestTemplate bean,使用'prototype'作用域,它只会检索一个新实例,任何自动装配都不会使用它字段。

答案 1 :(得分:0)

由于缺少LoadBalancerInterceptor,它确实失败了,但是可以简单地注入该类。 注入它,并删除@LoadBalanced批注:

java @Bean @Scope("prototype") RestTemplate loadBalancedTemplate(LoadBalancerInterceptor loadBalancerInterceptor) { RestTemplate template = new RestTemplate(); template.getInterceptors().add(loadBalancerInterceptor); return template; }