如何使用ServiceRegistry

时间:2012-04-12 06:05:34

标签: java

我遇到了一个问题,我编写了一个Class(EasybImpl)来实现EasybPlugin,但是当我迭代提供者时,我无法获得我写的EasybImpl支持。

我认为EasybImpl正在使用System类加载器,而控制台将类加载器打印为sun.misc.Launcher $ AppClassLoader。这有什么不对。

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

2 个答案:

答案 0 :(得分:2)

您是否将您的班级声明为服务提供商?

  

要声明服务提供者,services子目录放在META-INF目录中,该目录存在于每个JAR文件中。此目录包含每个服务提供者接口的文件,该文件在JAR文件中具有一个或多个实现类。例如,如果JAR文件包含名为com.mycompany.mypkg.MyServiceImpl的类,该类实现了javax.someapi.SomeService接口,则JAR文件将包含名为的文件:

     

META-INF / services / javax.someapi.SomeService

     

包含以下行:

     

com.mycompany.mypkg.MyService

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

答案 1 :(得分:0)

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: