1

I have a Spring Boot API that contains the following ApplicationConfig class:

@Configuration
public class ApplicationConfig {

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        addCustomMappings(modelMapper);
        return modelMapper;
    }

    @Bean
    @LoadBalanced // This annotation must be commented out when running on local machine.
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.build();
    }

}

When running locally, I must comment out the @LoadBalanced annotation on the restTemplate method for the API to function properly. This is not ideal. I would rather have this annotation automatically disabled based on the environment the app is running in. I am considering two approaches to solving this problem:

  1. I am already using Maven profiles in the pom. They are named local (default), dev, and prod. Currently these profiles are being used only to set a config value in the pom. I wonder if I could specify whether to disable the annotation in question using Maven profiles.

  2. I also have different application.yml files being delivered to the project by a config server based on the environment. Perhaps an environmental variable in the yml will give me the ability to disable the @LoadBalanced annotation.

Either way, I need to figure out how to get the annotation disabled. How might I go about doing this? I considered creating two versions of the restTemplate method (one with @LoadBalanced and one without), but I don't know a good way to conditionally call one vs the other. The method runs on startup due to some Spring magic I do no understand. Any ideas?

  • 1
    Have you tried researching Spring boot profiles? https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-profiles. I think you can disable non prod annotation based on the profile. – Zafar Nov 18 '20 at 22:59
  • This looks like it would work. I’ll give it a try when the workday begins tomorrow. Thank you. – Johnny Rocketfingers Nov 18 '20 at 23:02
  • 1
    Does this answer your question? [Are there anyway to disable annotation in spring4?](https://stackoverflow.com/questions/38986067/are-there-anyway-to-disable-annotation-in-spring4) – Marc Nov 19 '20 at 05:22

0 Answers0