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)?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With