Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot inject LoadBalanced annotated OAuth2RestTemplate

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)?

like image 705
Armin Balalaie Avatar asked May 16 '26 17:05

Armin Balalaie


1 Answers

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;
}
like image 68
Armin Balalaie Avatar answered May 18 '26 19:05

Armin Balalaie