title: Decide which of multiple implementations to use in Spring Boot app
body: <p>Given two (or more) implementations of a particular service API, what's the best way to pick which one to use at runtime in my app based on an application property?</p>
  
  <p>Example API:</p>
  
  <pre><code>public interface Greeting {
      String sayHello(String username);
  }
  </code></pre>
  
  <p>Implementations:</p>
  
  <pre><code>public class FriendlyGreeting implements Greeting {
      public String sayHello(String username) {
          return "Hello, " + username;
      }
  } 
  
  public class HostileGreeting implements Greeting {
      public String sayHello(String username) {
          return "Go away, " + username;
      }
  }
  </code></pre>
  
  <p>I've got a separate service class with an <code>@Autowired</code> constructor that takes an instance of <code>Greeting</code>.  What I want, is based upon a configuration property, to decide which greeting implementation gets injected and used.  I came up with using a configuration class to make that decision:</p>
  
  <pre><code>@Configuration
  public class GreetingConfiguration {
      private String selection;
  
      @Autowired
      public GreetingConfiguration(@Value("${greeting.type}") String type) {
          this.selection = type;
      }
  
      @Bean
      public Greeting provideGreeting() {
          if ("friendly".equals(selection)) {
              return new FriendlyGreeting();
          } else {
              return new HostileGreeting();
          }
      }
  }
  </code></pre>
  
  <p>Is this the <em>right</em> way to do what I want?   I went down the road of using <code>@Qualifier</code> on the implementations, and ended up with a mess where Spring saw 3 instances of my <code>Greeting</code> API, and I needed a configuration anyway to pick which implementation to use and return it with a unique qualifier name on it, and that feels worse than what I settled on.</p>