3

I am using Spring Cloud Angel.SR4. My Configuration class for creating an OAuth2RestTemplate bean is as follows:

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

    public OAuthClientConfiguration() {
    }

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

This configuration is totally fine since I am using this RestTemplate in a Feign RequestInterceptor for injecting access tokens to the feign requests. The problem is that when I annotate an autowired OAuth2RestTemplate with @LoadBalanced the dependency injection engine raises a NoSuchBeanDefinitionException exception. For example, the following would raise an exception:

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

and when I remove the @LoadBalanced, everything works fine. What is wrong with @LoadBalanced? Do I need any additional configurations (I already have @EnableEurekaClient)?

Armin Balalaie
  • 591
  • 1
  • 5
  • 17

2 Answers2

3

I found a workaround. The problem was that I had misunderstood the @LoadBalanced annotation. This is just a qualifier for the auto-created load-balanced RestTemplate bean, and it would not create a proxy around the annotated RestTemplate for injecting the load balancing capability.

After seeing this 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, I revised my OAuth2RestTemplate bean definition as follows, and it solved the problem.

@Bean
@Qualifier("MyOAuthRestTemplate")
public OAuth2RestTemplate restTemplate(RestTemplateCustomizer customizer) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(this.resource);
    customizer.customize(restTemplate);
    return restTemplate;
}
Armin Balalaie
  • 591
  • 1
  • 5
  • 17
1

I used @LoadBalanced with restTemplate in spring cloud with ribbon behind the scenes.

adding @LoadBalanced in the bean definition it works like this:

in my class i have

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

and in my configuration class i have:

@Configuration
public class ServiceConfig {

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

}

this works for me

I hope that this can help

spencergibb
  • 24,471
  • 6
  • 69
  • 75
Valerio Vaudi
  • 4,199
  • 2
  • 24
  • 23