DEV Community

Aashutosh Poudel
Aashutosh Poudel

Posted on

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

Top comments (0)