1

Java SPI is simple to use when we want to find all available implementations of an interface or abstract class and perform an action with each:

ServiceLoader.load(SomeService.class)
    .forEach(service -> service.doSomething());

What is the idiom for choosing a single implementation from multiple available implementations? There are many services I can think of that don't make sense to operate with multiple instances.

We can use iterator().next() to just find the first implementation that comes back from ServiceLoader, but this doesn't offer the user a way to select which specific implementation they want to be picked up, if necessary. As far as I can tell, the iteration order is somewhat random and based upon the classpath ordering of the META-INF/services files which is not consistent.

Surely I am missing something and this is already taken care of without having to write our own 'if system property is set, load this class, else iterator.next from ServiceLoader'

Ivan G.
  • 700
  • 8
  • 19

0 Answers0