Monthly Archives: September 2013

Choosing implementation with ServiceLoader in Java

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

package com.company.test;

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: com.company.test.SomeIface.

2. Fill all possible implementations in it:

com.company.test.Some1
com.company.test.Some2
com.company.test.Some3

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 = it.next();
} else if () {
    // use second
    impl = it.next();
} else {
    // use third
    impl = it.next();
}

That’s all!

See also,
ServiceLoader