My application makes REST calls to 2 different web services. The first one uses basic authentication and the second does not. I would like to define a RestTemplateBuilder bean with the basic auth credentials configured & use it for the basic-auth case and use the default Spring configured RestTemplateBuilder for the non-basic-auth case.
But defining the custom RestTemplateBuilder bean fails context load(details below).
Bean definition:
@Configuration
class RestTemplateBuilderConfig {
@Bean
public RestTemplateBuilder customRestTemplateBuilder(RestTemplateBuilder springConfiguredRestTemplateBuilder) {
return
springConfiguredRestTemplateBuilder
.basicAuthentication("user", "password");
}
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Context load failure:
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| customRestTemplateBuilder defined in class path resource [com/example/demo/RestTemplateBuilderConfig.class]
└─────┘
As I understand, the spring initialized bean should be injected into customRestTemplateBuilder(...) and the return value should result in a new bean with name customRestTemplateBuilder. Appreciate any pointers on what could be going wrong?
The answers to this question suggest defining RestTemplate beans. But that would prevent usage of RestClientTest in my tests.
I could inject the Spring initialized RestTemplateBuilder into my services and set the credentials before restTemplateBuilder.build() in each of the services. But then the logic to set the credentials will be distributed across the services (violating DRY).
Defining a new RestTemplateBuilder resolves the issue but Spring initialization is lost.
@Bean
public RestTemplateBuilder customRestTemplateBuilder() {
return
new RestTemplateBuilder()
.basicAuthentication("user", "password");
}