title: Spring ServiceLocator or pure factory pattern?
body: <p>99% of my dependency is manage with DI pattern via @Autowired Spring annotation.</p>
  
  <p>Nevertheless in a particular scenario, I can't determine which implementation to be used until run-time.</p>
  
  <p>The most known case, is the multiple implementation of parsers.</p>
  
  <p><strong>The first solution is to used multiple @Autowired (ugly mode)</strong></p>
  
  <pre><code>Interface Parser {
      &lt;T&gt; T parse();
  }
  
  @Component("JsonParser")
  class JsonParser implements Parser {
      ...
  }
  
  @Component("XmlParser")
  class XmlParser implements Parser {
      ...
  }
  
  class MyService {
      @Autowired
      @Qualifier("XmlParser")
      Parser xmlParser;
  
      @Autowired
      @Qualifier("JsonParser")
      Parser jsonParser;
  
      ...     
  }
  </code></pre>
  
  <p>But if I have a large number of implementation that can be not acceptable.</p>
  
  <p><strong>The second solution is to used ServiceLocator from Spring</strong></p>
  
  <pre><code>interface ParserServiceLocatorFactory {
      public Parser getParser(String parserName);
  }
  
  interface Parser {
      &lt;T&gt; T parse();
  }
  
  @Component("JsonParser")
  class JsonParser implements Parser {
      ...
  }
  
  @Component("XmlParser")
  class XmlParser implements Parser {
      ...
  }
  
  class MyService {
      @Autowired 
      ServiceFactory parserServiceLocatorFactory;
  
      void exampleMethod() {
          Parser xmlParser = parserServiceLocatorFactory.getParser("XmlParser");
      }
  }
  </code></pre>
  
  <p>This way to do seems right to me but compared with the third solution?</p>
  
  <p><strong>The third solution is to used pure factory pattern and inject it.</strong></p>
  
  <pre><code>@Component
  public ParserFactory {
      Parser getParser(String parserName) {
          ...
      }
  }
  
  interface Parser {
      &lt;T&gt; T parse();
  }
  
  @Component("JsonParser")
  class JsonParser implements Parser {
      ...
  }
  
  @Component("XmlParser")
  class XmlParser implements Parser {
      ...
  }
  
  class MyService {
      @Autowired 
      ParserFactory parserFactory
  
      void exampleMethod() {
          Parser xmlParser = parserFactory.getParser("XmlParser");
      }
  }
  </code></pre>
  
  <p>If you have pro/con for the previous solutions, or even better solution for my problem?</p>
  
  <p>PS: it's pseudo code I may miss some small things :)</p>