1

I am on spring boot 1.3.3 version, I have a requirement where my spring boot application need to call endpoint(s) based on env passed, which means if env passed as Dev i would need to call devendpoint, if env passed as Dev1 then need to call dev1endpoint and so on. So how can I do this ? Do I need to create multiple restTemplate instances ? Should I construct the resttemplate dynamically based on env passed ? As part of constructing resttemplate i would also need to add appllicable interceptor based on env selected. Plesae suggest.

2 Answers 2

1

You can have two beans of the same class. One can be labeled as the primary, and the use on the @Autowired can specify which one to use with the @Qualifier.

Example:

@Configuration
public class MyConfig {
  @Bean
  @Primary
  public RestTemplate typicalConfig() {
    // various configs on your rest template
    return new RestTemplate();
  }

  @Bean
  public RestTemplate lessTypical() {
    // various alternate configurations
    return new RestTemplate();
  }
}

Now in your service class:

@Service
public class MyService {

  @Autowired
  RestTemplate typicalRestTemplate;

  @Autowired
  @Qualifier("lessTypical")
  private RestTemplate alternateRestTemplate;

  ...
}
-1

correct me if I didn't understand your question. I understand that you are going to have different environments but you are going to change this endpoints in runtime depends on some information or whatever, but I don't understand the part when you said you have to create multiple instances of restTemplate for that environments, from my experience on spring boot applications you don't have to do things like that, You just have to create your restTemplate configuration bean.

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

And then injected that object on your services class and do whatever you want with them. I recommend you to read the follow article about restTempalte may this could help you http://www.baeldung.com/rest-template

2
  • In my requirement, based on env passed I would need to set the relevant interceptor (Dev) to resttemplate.This interceptor contains the hmac details for that end point(Dev env ).So next time when different env (Dev1)passed I would need to remove Dev env interceptor from resttemplate and then add Dev1 env interceptor to restemplate.So this way i can resuse the same resttemplate instance.Is that possible to do this ?
    – Raj
    Mar 6, 2017 at 1:15
  • I have a similar requirement due to differing authentication requirements. It's a pity this didn't answer the question asked.
    – Kieveli
    Nov 19, 2018 at 16:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.