0

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");
    }

2 Answers 2

0

You have no choice but define 2 bean in your context, which maybe share the same initialization logic by defining a init method for both. As bean level reusing is not possible as shows in your example.

Sign up to request clarification or add additional context in comments.

Comments

0

RestTemplateBuilder is used to build single RestTemplates.

Easiest is to just build two restTemplates and use a @Qualifier for each RestTemplate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.