【问题标题】:Cannot inject LoadBalanced annotated OAuth2RestTemplate无法注入 LoadBalanced 注释的 OAuth2RestTemplate
【发布时间】:2016-04-26 20:01:39
【问题描述】:

我正在使用 Spring Cloud Angel.SR4。我用于创建OAuth2RestTemplate bean 的配置类如下:

@Configuration
public class OAuthClientConfiguration {
    @Autowired
    private MyClientCredentialsResourceDetails resource;

    public OAuthClientConfiguration() {
    }

    @Bean
    @Qualifier("MyOAuthRestTemplate")
    public OAuth2RestTemplate restTemplate() {
        return new OAuth2RestTemplate(this.resource);
    }
}

这个配置完全没问题,因为我在 Feign RequestInterceptor 中使用这个 RestTemplate 将访问令牌注入到 feign 请求中。问题是当我用@LoadBalanced 注释自动连接的OAuth2RestTemplate 时,依赖注入引擎会引发NoSuchBeanDefinitionException 异常。例如,以下会引发异常:

@LoadBalanced
@Autowired
@Qualifier("MyOAuthRestTemplate")
private OAuth2RestTemplate restTemplate;

当我删除@LoadBalanced 时,一切正常。 @LoadBalanced 有什么问题?我是否需要任何额外的配置(我已经有@EnableEurekaClient)?

【问题讨论】:

    标签: spring spring-boot spring-cloud spring-oauth2 spring-cloud-connectors


    【解决方案1】:

    我找到了解决方法。问题是我误解了@LoadBalanced 注释。这只是自动创建的负载平衡RestTemplate bean 的限定符,它不会围绕带注释的RestTemplate 创建代理以注入负载平衡功能。

    看到这个https://github.com/spring-cloud/spring-cloud-commons/blob/v1.0.3.RELEASE/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java后,我修改了我的OAuth2RestTemplate bean定义如下,问题解决了。

    @Bean
    @Qualifier("MyOAuthRestTemplate")
    public OAuth2RestTemplate restTemplate(RestTemplateCustomizer customizer) {
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resource);
        customizer.customize(restTemplate);
        return restTemplate;
    }
    

    【讨论】:

      【解决方案2】:

      我在 Spring Cloud 中使用 @LoadBalanced 和 restTemplate,并在幕后使用功能区。

      在 bean 定义中添加 @LoadBalanced 即可 像这样:

      在我的课上

      @Autowired  
      @LoadBalanced  
      @Qualifier("bookRepositoryServiceRestTemplate") private RestTemplate bookRepositoryServiceRestTemplate;
      

      在我的配置类中我有:

      @Configuration
      public class ServiceConfig {
      
          @Bean
          @LoadBalanced
          public RestTemplate bookRepositoryServiceRestTemplate(SpringClientFactory clientFactory, LoadBalancerClient loadBalancer){
              RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory = new RibbonClientHttpRequestFactory(clientFactory,loadBalancer);
              return new RestTemplate(ribbonClientHttpRequestFactory);
          }
          ....
      
      }
      

      这对我有用

      希望对你有帮助

      【讨论】:

      • 你不应该需要@Qualifier("bookRepositoryServiceRestTemplate")
      • 是的,我知道这只是我的习惯
      猜你喜欢
      • 2018-11-02
      • 2021-09-09
      • 2021-11-11
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2019-09-01
      • 2021-04-11
      相关资源
      最近更新 更多