Attis Wong
Attis Wong

Reputation: 11

How to use ServiceRegistry

I run into a problem, I wrote a Class(EasybImpl) which implement EasybPlugin, but when I iterate providers, I could not get the EasybImpl support that i wrote.

I thought the EasybImpl is using the System classloader and the console println the classloader as sun.misc.Launcher$AppClassLoader. what's wrong with it.

    Iterator providers = ServiceRegistry.lookupProviders(EasybPlugin.class, 
                         ClassLoader.getSystemClassLoader());

Upvotes: 1

Views: 4049

Answers (2)

Thomas W
Thomas W

Reputation: 14164

Four steps are required:

  • you build a META-INF/services subdirectory into your JAR file.
  • in the 'services' directory, create a file for each service you are implementing. (in your case, this would be file META-INFA/services/my.package.EasybPlugin).
  • in that file, declare the name of your implementation class(es).
  • you can then use the java.util.ServiceLoader API to discover & load registered services.

An example of the service provider file:

# providers of EasyBPlugin SPI
# (comment lines begin with pound)
my.package.StandardEasybPlugin

You can then find and load service implementations like this:

ServiceLoader<EasybPlugin> loader = ServiceLoader.load(EasybPlugin.class);
for (EasybPlugin plugin : loader) {
    // ...
}

Note 1: the ServiceProvider API you were looking at is really targetted at Image IO, eg reading image file formats. ServiceLoader is for general use & should be preferred unless your purpose is not reading images.

There's a more detailed tutorial here: http://literatejava.com/extensibility/java-serviceloader-extensible-applications/

References:

Upvotes: 0

Frank
Frank

Reputation: 1489

Did you declare your class as a service provider?

To declare a service provider, a services subdirectory is placed within the META-INF directory that is present in every JAR file. This directory contains a file for each service provider interface that has one or more implementation classes present in the JAR file. For example, if the JAR file contained a class named com.mycompany.mypkg.MyServiceImpl which implements the javax.someapi.SomeService interface, the JAR file would contain a file named:

META-INF/services/javax.someapi.SomeService

containing the line:

com.mycompany.mypkg.MyService

http://docs.oracle.com/javase/6/docs/api/javax/imageio/spi/ServiceRegistry.html

Upvotes: 2

Related Questions