DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

8 2

Creating multiple RestTemplates in Java/Spring

In Spring boot I needed to call two different API endpoints that had different credentials and authentication methods. So, I needed a way to create two different RestTeamplates in Spring that handled the two different API calls.

@Configuration
public class RestTemplateConfig {
  @Bean(name = "basicAuth")
  @Primary
  public RestTemplate basicAuthRestTemplate(RestTemplateBuilder builder) {
    // various configs on your rest template
    return builder().build();
  }

  @Bean(name = "jwtAuth")
  public RestTemplate jwtAuthRestTemplate(RestTemplateBuilder builder) {
    // various alternate configurations
    return builder().build();
  }
}
Enter fullscreen mode Exit fullscreen mode

Now in your service the two rest templates can be imported by specifying a qualifier

@Service
public class MyService {

  @Autowired
  RestTemplate basicAuthRestTemplate;

  @Autowired
  @Qualifier("jwtAuth")
  private RestTemplate jwtAuthRestTemplate;

  ...
}
Enter fullscreen mode Exit fullscreen mode

Source

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay