Last modified 6 years ago Last modified on 05/05/2011 09:49:04

Service discovering with annotation @ServiceProvider

Java offers a proper way for service discovering with its Meta-inf services specification, see this article for learning more about that.

Although this system is efficient, editing plain text files in META-INF/services/ could be a pain because they are not checked during the compilation. Netbeans offers a solution by introducing the annotation @ServiceProvider.

@ServiceProvider and maven 3

To be able to use this annotation and to ensure its process during compilation, you have to:

  • add the netbeans repository to your project:
            <repository>
                <id>netbeans</id>
                <url>http://bits.netbeans.org/maven2/</url>
            </repository>
    
  • add the lookup as dependency of your project:
            <dependency>
                <groupId>org.netbeans.api</groupId>
                <artifactId>org-openide-util-lookup</artifactId>
                <version>RELEASE70</version>
            </dependency>
    
  • then you can use the annotation in your code, and check that the files are correctly created in your jar during packaging phase:
    @ServiceProvider(service=MyService.class)
    public class MyImplementation {
    
  • for retrieving registered services, you should use org.openide.util. Lookup utility class:
    Lookup.getDefault().lookupResult(MyService.class).allClasses()
    

or

Lookup.getDefault().lookupResult(MyService.class).allInstances()

When I was using maven in version 2.x, I should specify the version of the compiler by putting something like that in your pom:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <!-- default version doesn't support annotation processing
                required for @ServiceProvider -->
                <version>2.3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>