Introduction
JDK 6 introduced ServiceLoader. ServiceLoader loads things based on flat files in the directory META-INF/services from the Java classpath. The mechanism of using META-INF/services has been around since JDK 1.3, under the name of Java Extension Mechanism.
This library aims to provide a backport compatibility of Service Provider Interface APIs to Java5.
To use it, just add the following dependency to your pom.xml:
<dependencies>
...
<dependency>
<groupId>org.99soft.commons</groupId>
<artifactId>backport-spi</artifactId>
<version>XX.XX</version>
</dependency>
...
</dependencies>or, for systems that have to be compiled in both JDKs 5 and 6, add it in a JDK5 proper profile:
<profiles>
<profile>
<id>java-1.5-detected</id>
<activation>
<jdk>1.5</jdk>
</activation>
<dependencies>
[...]
<dependency>
<groupId>org.99soft.commons</groupId>
<artifactId>backport-spi</artifactId>
<version>XX.XX</version>
</dependency>
[...]
</dependencies>
[...]
</profile>
</profiles>Now you can use the backported ServiceLoader:
import java.util.ServiceLoader;
...
ServiceLoader<HelloService> ldr = ServiceLoader.load( HelloService.class );
for ( HelloService provider : ldr )
{
doSomething( provider );
}where HelloService is the interface/abstract class of the service.
Discovering Services types only
Starting from 1.0.1 version, the Backport SPI introduces a new feature to allow users to iterate over Service Class iterator, to know only the types which implement the discovered Service:
import java.util.ServiceLoader;
...
ServiceLoader<HelloService> ldr = ServiceLoader.load( HelloService.class );
Iterator<Class<? extends HelloService>> serviceClassIterator = ldr.typesIterator();
while ( serviceClassIterator.hasNext() )
{
// do something
}