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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay