Monthly Archives: September 2013

Choosing implementation with ServiceLoader in Java

Java has a internal dependency injection mechanism. Cool really?
For ex. you have an interface and set of specific implementations:


SomeIface {}
Some1 implements SomeIface {}
Some2 implements SomeIface {}
Some3 implements SomeIface {}

In order to make DI possible just do next things:
1. Create file with full qualified name of interface in “META-INF/services” folder:

2. Fill all possible implementations in it:

3. In runtime (or in init phase of your app.) use next:

SomeIface impl = null;
Iterator it = ServiceLoader.load(SomeIface.class).iterator();

if () {
    // use first
    impl =;
} else if () {
    // use second
    impl =;
} else {
    // use third
    impl =;

That’s all!

See also,