java.util.ServiceLoader类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(7.7k)|赞(0)|评价(0)|浏览(156)

本文整理了Java中java.util.ServiceLoader类的一些代码示例,展示了ServiceLoader类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ServiceLoader类的具体详情如下:
包路径:java.util.ServiceLoader
类名称:ServiceLoader

ServiceLoader介绍

[英]A service-provider loader.

A service provider is a factory for creating all known implementations of a particular class or interface S. The known implementations are read from a configuration file in META-INF/services/. The file's name should match the class' binary name (such as java.util.Outer$Inner).

The file format is as follows. The file's character encoding must be UTF-8. Whitespace is ignored, and # is used to begin a comment that continues to the next newline. Lines that are empty after comment removal and whitespace trimming are ignored. Otherwise, each line contains the binary name of one implementation class. Duplicate entries are ignored, but entries are otherwise returned in order (that is, the file is treated as an ordered set).

Given these classes:

package a.b.c; 
public interface MyService { ... } 
public class MyImpl1 implements MyService { ... } 
public class MyImpl2 implements MyService { ... }

And this configuration file (stored as META-INF/services/a.b.c.MyService):

# Known MyService providers. 
a.b.c.MyImpl1  # The original implementation for handling "bar"s. 
a.b.c.MyImpl2  # A later implementation for "foo"s.

You might use ServiceProvider something like this:

for (MyService service : ServiceLoader.load(MyService.class)) { 
if (service.supports(o)) { 
return service.handle(o); 
} 
}

Note that each iteration creates new instances of the various service implementations, so any heavily-used code will likely want to cache the known implementations itself and reuse them. Note also that the candidate classes are instantiated lazily as you call next on the iterator: construction of the iterator itself does not instantiate any of the providers.
[中]服务提供者加载器。
服务提供者是创建特定类或接口的所有已知实现的工厂。已知实现是从META-INF/services/中的配置文件读取的。文件名应与类的二进制名称匹配(例如java.util.Outer$Inner)。
文件格式如下。文件的字符编码必须是UTF-8。空白被忽略,并且#用于开始一条评论,该评论将延续到下一行。删除注释和删除空白后为空的行将被忽略。否则,每行包含一个实现类的二进制名称。重复的条目会被忽略,但条目会按顺序返回(也就是说,文件被视为一个有序集)。
考虑到这些类别:

package a.b.c; 
public interface MyService { ... } 
public class MyImpl1 implements MyService { ... } 
public class MyImpl2 implements MyService { ... }

和此配置文件(存储为META-INF/services/a.b.c.MyService):

# Known MyService providers. 
a.b.c.MyImpl1  # The original implementation for handling "bar"s. 
a.b.c.MyImpl2  # A later implementation for "foo"s.

您可以使用ServiceProvider,如下所示:

for (MyService service : ServiceLoader.load(MyService.class)) { 
if (service.supports(o)) { 
return service.handle(o); 
} 
}

请注意,每次迭代都会创建各种服务实现的新实例,因此任何频繁使用的代码都可能希望缓存已知的实现本身并重用它们。还请注意,候选类是在您调用迭代器的下一步时延迟实例化的:迭代器本身的构造不会实例化任何提供程序。

代码示例

代码示例来源:origin: ctripcorp/apollo

public static <S> Iterator<S> loadAll(Class<S> clazz) {
  ServiceLoader<S> loader = ServiceLoader.load(clazz);

  return loader.iterator();
 }
}

代码示例来源:origin: apache/incubator-druid

private void addAllFromCurrentClassLoader()
{
 ServiceLoader
   .load(serviceClass, Thread.currentThread().getContextClassLoader())
   .forEach(impl -> tryAdd(impl, "classpath"));
}

代码示例来源:origin: prestodb/presto

@Override
  public ServiceLoader<T> run() {
    return (classLoader == null) ?
        ServiceLoader.load(clazz) : ServiceLoader.load(clazz, classLoader);
  }
});

代码示例来源:origin: alibaba/Sentinel

@Override
public Iterator<CommandHandler> iterator() {
  return serviceLoader.iterator();
}

代码示例来源:origin: redisson/redisson

@Override
  public ServiceLoader<T> run() {
    return (classLoader == null) ?
        ServiceLoader.load(clazz) : ServiceLoader.load(clazz, classLoader);
  }
});

代码示例来源:origin: jeremylong/DependencyCheck

/**
   * Returns an Iterator for all instances of the CachedWebDataSource
   * interface.
   *
   * @return an iterator of CachedWebDataSource.
   */
  public Iterator<CachedWebDataSource> getDataSources() {
    return loader.iterator();
  }
}

代码示例来源:origin: gocd/gocd

private IVProvider getIvProviderInstance() {
  if (ivProvider == null) {
    synchronized (AESEncrypter.class) {
      if (ivProvider == null) {
        ivProvider = ServiceLoader.load(IVProvider.class).iterator().next();
      }
    }
  }
  return ivProvider;
}

代码示例来源:origin: dropwizard/dropwizard

public ViewBundle() {
  this(ServiceLoader.load(ViewRenderer.class));
}

代码示例来源:origin: apache/incubator-druid

private void addAllFromFileSystem()
{
 for (File extension : getExtensionFilesToLoad(extensionsConfig)) {
  log.info("Loading extension [%s] for class [%s]", extension.getName(), serviceClass);
  try {
   final URLClassLoader loader = getClassLoaderForExtension(
     extension,
     extensionsConfig.isUseExtensionClassloaderFirst()
   );
   ServiceLoader.load(serviceClass, loader).forEach(impl -> tryAdd(impl, "local file system"));
  }
  catch (Exception e) {
   throw Throwables.propagate(e);
  }
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) {
  Iterator<?> it = serviceLoader.iterator();
  if (!it.hasNext()) {
    throw new IllegalStateException(
        "ServiceLoader could not find service for type [" + getServiceType() + "]");
  }
  return it.next();
}

代码示例来源:origin: SonarSource/sonarqube

Set<CoreExtension> load(ClassLoader classLoader) {
  ServiceLoader<CoreExtension> loader = ServiceLoader.load(CoreExtension.class, classLoader);
  return ImmutableSet.copyOf(loader.iterator());
 }
}

代码示例来源:origin: PipelineAI/pipeline

private static <T> T findService(
    Class<T> spi, 
    ClassLoader classLoader) throws ServiceConfigurationError {
  
  ServiceLoader<T> sl = ServiceLoader.load(spi,
      classLoader);
  for (T s : sl) {
    if (s != null)
      return s;
  }
  return null;
}

代码示例来源:origin: stagemonitor/stagemonitor

private List<Class<? extends SpanEventListenerFactory>> getFactoryClasses() {
    List<Class<? extends SpanEventListenerFactory>> spanEventListenerFactories = new ArrayList<>();
    final ServiceLoader<SpanEventListenerFactory> serviceLoader = ServiceLoader.load(SpanEventListenerFactory.class);
    serviceLoader.forEach(e -> spanEventListenerFactories.add(e.getClass()));
    return spanEventListenerFactories;
  }
}

代码示例来源:origin: org.springframework/spring-beans

@Override
protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) {
  Iterator<?> it = serviceLoader.iterator();
  if (!it.hasNext()) {
    throw new IllegalStateException(
        "ServiceLoader could not find service for type [" + getServiceType() + "]");
  }
  return it.next();
}

代码示例来源:origin: swagger-api/swagger-core

@Override
  public boolean exists(String path) {

    try {
      ServiceLoader<OpenAPIConfigBuilder> loader = ServiceLoader.load(OpenAPIConfigBuilder.class);
      if (loader.iterator().hasNext()) {
        loader.iterator().next();
        return true;
      }
      return false;
    } catch (Exception e) {
      return false;
    }
  }
}

代码示例来源:origin: Graylog2/graylog2-server

private Iterable<Plugin> loadClassPathPlugins() {
  return ServiceLoader.load(Plugin.class);
}

代码示例来源:origin: stagemonitor/stagemonitor

@Test
public void testLoadedViaServiceLoader() throws Exception {
  List<Class<? extends SpanReporter>> spanReporters = new ArrayList<>();
  ServiceLoader.load(SpanReporter.class).forEach(reporter -> spanReporters.add(reporter.getClass()));
  assertTrue(spanReporters.contains(LoggingSpanReporter.class));
}

代码示例来源:origin: yu199195/Raincat

public static <S> S loadFirst(final Class<S> clazz) {
  final ServiceLoader<S> loader = loadAll(clazz);
  final Iterator<S> iterator = loader.iterator();
  if (!iterator.hasNext()) {
    throw new IllegalStateException(String.format(
        "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
        clazz.getName()));
  }
  return iterator.next();
}

代码示例来源:origin: ch.qos.logback/logback-classic

public static <T> T loadFromServiceLoader(Class<T> c) {
  ServiceLoader<T> loader = ServiceLoader.load(c, getServiceLoaderClassLoader());
  Iterator<T> it = loader.iterator();
  if (it.hasNext())
    return it.next();
  return null;
}

代码示例来源:origin: wildfly/wildfly

/**
 * Construct a new instance.
 *
 * @param classLoader the class loader to use as the basis of the provider search, or {@code null} to use the system
 *      or bootstrap class loader
 */
public ServiceLoaderSaslServerFactory(final ClassLoader classLoader) {
  this(ServiceLoader.load(SaslServerFactory.class, classLoader));
}

相关文章