当前位置: 首页>>代码示例>>Java>>正文


Java ServiceLoader类代码示例

本文整理汇总了Java中java.util.ServiceLoader的典型用法代码示例。如果您正苦于以下问题:Java ServiceLoader类的具体用法?Java ServiceLoader怎么用?Java ServiceLoader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ServiceLoader类属于java.util包,在下文中一共展示了ServiceLoader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createObjectMapper

import java.util.ServiceLoader; //导入依赖的package包/类
public static ObjectMapper createObjectMapper() {
    final YAMLFactory yamlFactory = new YAMLFactory()
        .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false)
        .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
        .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true)
        .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false);

    ObjectMapper mapper = new ObjectMapper(yamlFactory)
        .registerModule(new Jdk8Module())
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
        .enable(SerializationFeature.INDENT_OUTPUT)
        .disable(SerializationFeature.WRITE_NULL_MAP_VALUES);

    for (Step step : ServiceLoader.load(Step.class, YamlHelpers.class.getClassLoader())) {
        mapper.registerSubtypes(new NamedType(step.getClass(), step.getKind()));
    }

    return mapper;
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:20,代码来源:YamlHelpers.java

示例2: findServiceProvider

import java.util.ServiceLoader; //导入依赖的package包/类
private static <T> T findServiceProvider(final Class<T> type)
        throws DatatypeConfigurationException
{
    try {
        return AccessController.doPrivileged(new PrivilegedAction<T>() {
            public T run() {
                final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
                final Iterator<T> iterator = serviceLoader.iterator();
                if (iterator.hasNext()) {
                    return iterator.next();
                } else {
                    return null;
                }
            }
        });
    } catch(ServiceConfigurationError e) {
        final DatatypeConfigurationException error =
                new DatatypeConfigurationException(
                    "Provider for " + type + " cannot be found", e);
        throw error;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:FactoryFinder.java

示例3: loadProviderAsService

import java.util.ServiceLoader; //导入依赖的package包/类
private static AsynchronousChannelProvider loadProviderAsService() {
    ServiceLoader<AsynchronousChannelProvider> sl =
        ServiceLoader.load(AsynchronousChannelProvider.class,
                           ClassLoader.getSystemClassLoader());
    Iterator<AsynchronousChannelProvider> i = sl.iterator();
    for (;;) {
        try {
            return (i.hasNext()) ? i.next() : null;
        } catch (ServiceConfigurationError sce) {
            if (sce.getCause() instanceof SecurityException) {
                // Ignore the security exception, try the next provider
                continue;
            }
            throw sce;
        }
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:18,代码来源:AsynchronousChannelProvider.java

示例4: loadBuilders

import java.util.ServiceLoader; //导入依赖的package包/类
private static Map<String, HandlerBuilder> loadBuilders(final ClassLoader classLoader) {
    ServiceLoader<HandlerBuilder> loader = ServiceLoader.load(HandlerBuilder.class, classLoader);
    final Map<String, HandlerBuilder> ret = new HashMap<>();
    for (HandlerBuilder builder : loader) {
        if (ret.containsKey(builder.name())) {
            if (ret.get(builder.name()).getClass() != builder.getClass()) {
                throw UndertowMessages.MESSAGES.moreThanOneHandlerWithName(builder.name(), builder.getClass(), ret.get(builder.name()).getClass());
            }
        } else {
            ret.put(builder.name(), builder);
        }
    }
    return ret;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:15,代码来源:HandlerParser.java

示例5: init

import java.util.ServiceLoader; //导入依赖的package包/类
/**
 * Load {@link BeanPropertyPostProcessor}s from <code>META-INF/services</code> extensions.
 * @param classLoader ClassLoader to use
 * @return {@link BeanPropertyPostProcessor}s list, empty if none found
 */
private void init(final ClassLoader classLoader) {
	LOGGER.debug(() -> "Load BeanPropertyPostProcessors for classloader [" + classLoader
			+ "] using ServiceLoader with service name: " + BeanPropertyPostProcessor.class.getName());
	Iterable<BeanPropertyPostProcessor> postProcessors = AccessController
			.doPrivileged(new PrivilegedAction<Iterable<BeanPropertyPostProcessor>>() {
				@Override
				public Iterable<BeanPropertyPostProcessor> run() {
					return ServiceLoader.load(BeanPropertyPostProcessor.class, classLoader);
				}
			});
	postProcessors.forEach(pr -> {
		propertyPostProcessors.add(pr);
		LOGGER.debug(() -> "Loaded and registered BeanPropertyPostProcessor [" + pr + "] for classloader ["
				+ classLoader + "]");
	});
	// sort by priority
	Collections.sort(propertyPostProcessors, PRIORITY_COMPARATOR);
}
 
开发者ID:holon-platform,项目名称:holon-core,代码行数:24,代码来源:DefaultBeanIntrospector.java

示例6: validateServiceIsLocatableViaServiceLoader

import java.util.ServiceLoader; //导入依赖的package包/类
@Test
public void validateServiceIsLocatableViaServiceLoader() {
    ServiceLoader<Processor> loader = ServiceLoader.<Processor> load(Processor.class);
    Iterator<Processor> iter = loader.iterator();
    boolean pubJmsPresent = false;
    boolean consumeJmsPresent = false;
    while (iter.hasNext()) {
        Processor p = iter.next();
        if (p.getClass().getSimpleName().equals(PublishJMS.class.getSimpleName())) {
            pubJmsPresent = true;
        } else if (p.getClass().getSimpleName().equals(ConsumeJMS.class.getSimpleName())) {
            consumeJmsPresent = true;
        }

    }
    assertTrue(pubJmsPresent);
    assertTrue(consumeJmsPresent);
}
 
开发者ID:lsac,项目名称:nifi-jms-jndi,代码行数:19,代码来源:CommonTest.java

示例7: main

import java.util.ServiceLoader; //导入依赖的package包/类
public static void main(String[] args) {
    ServiceLoader<Analysis> analyses = ServiceLoader.load(Analysis.class);
  //  analyses.stream().map(ServiceLoader.Provider::get).forEach(analyzer -> System.out.println(analyzer.getName()));
    Set<Analysis> collect = analyses.stream()
                                    .filter(p -> isAnno(p.type()))
                                    .map(ServiceLoader.Provider::get).collect(Collectors.toSet());

    Person nao = new Person(0, 0);
    Person miniperson = new Person(10, 0);
    Person minperson = new Person(1001, 0);
    Person minxperson = new Person(1001, 11);
    Person maxperson = new Person(100000, 11);
    Person maxxperson = new Person(100000, 26);
    Person poorperson = new Person(100000, 0);

    collect.forEach(p->System.out.println(p.analyze(maxxperson)));


}
 
开发者ID:kkTranslation,项目名称:Java-9-Spring-Webflux,代码行数:20,代码来源:Gui.java

示例8: DefaultSqlConfig

import java.util.ServiceLoader; //导入依赖的package包/类
/**
 * コンストラクタ
 *
 * @param connectionSupplier コネクションサプライヤ
 * @param loadPath SQLファイルの読み込みルートパス
 */
private DefaultSqlConfig(final ConnectionSupplier connectionSupplier, final String loadPath) {
	super();
	this.connectionSupplier = connectionSupplier;

	this.sqlManager = new SqlManagerImpl(loadPath);
	this.sqlFilterManager = new SqlFilterManagerImpl();
	this.sqlContextFactory = new SqlContextFactoryImpl();
	this.entityHandler = new DefaultEntityHandler();

	this.dialect = StreamSupport.stream(ServiceLoader.load(Dialect.class).spliterator(), false).filter(d -> d.accept(connectionSupplier)).findFirst().orElseGet(DefaultDialect::new);

	this.sqlAgentFactory = new SqlAgentFactoryImpl(this);

	initialize();
}
 
开发者ID:future-architect,项目名称:uroborosql,代码行数:22,代码来源:DefaultSqlConfig.java

示例9: findServices

import java.util.ServiceLoader; //导入依赖的package包/类
/**
 * Looks for all "META-INF/services/[className]" files and
 * create one instance for each class name found inside this file.
 */
private <T> List<T> findServices(Class<T> clazz) {
    final List<T> result = new ArrayList<>();
    final boolean debug = getDebugPropertyValue();
    try {
        // TCCL allows user plugins to be loaded even if xjc is in jdk
        // We have to use our SecureLoader to obtain it because we are trying to avoid SecurityException
        final ClassLoader tccl = SecureLoader.getContextClassLoader();
        final ServiceLoader<T> sl = ServiceLoader.load(clazz, tccl);
        for (T t : sl)
            result.add(t);
    } catch (Throwable e) {
        // ignore any error
        StringWriter w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        pluginLoadFailure = w.toString();
        if (debug)
            System.out.println(pluginLoadFailure);
    }
    return result;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:Options.java

示例10: loadTokenParser

import java.util.ServiceLoader; //导入依赖的package包/类
@BeforeClass(alwaysRun=true)
public static void loadTokenParser() throws Exception {
    System.out.printf("TokenValidationTest.initClass\n");
    publicKey = TokenUtils.readPublicKey("/publicKey.pem");
    if(publicKey == null) {
        throw new IllegalStateException("Failed to load /publicKey.pem resource");
    }

    // Load the ITokenParser via the ServiceLoader
    ServiceLoader<ITokenParser> serviceLoader = ServiceLoader.load(ITokenParser.class);
    if(serviceLoader.iterator().hasNext() == false) {
        // Try to obtain ITokenParser via CDI
        tokenParser = CDI.current().select(ITokenParser.class).get();
        if(tokenParser == null) {
            throw new IllegalStateException(String.format("An %s service provider or producer is required", ITokenParser.class.getName()));
        }
    }
    else {
        tokenParser = serviceLoader.iterator().next();
        if (tokenParser == null) {
            throw new IllegalStateException(String.format("Service provider for %s  produced a null parser", ITokenParser.class.getName()));
        }
    }
    System.out.printf("Using ITokenParser: %s\n", tokenParser);
}
 
开发者ID:eclipse,项目名称:microprofile-jwt-auth,代码行数:26,代码来源:TokenValidationTest.java

示例11: testWithCustomLayer1

import java.util.ServiceLoader; //导入依赖的package包/类
/**
 * Basic test of ServiceLoader.load, using the class loader for
 * a module in a custom layer as the context.
 */
@Test
public void testWithCustomLayer1() {
    ModuleLayer layer = createCustomLayer("bananascript");

    ClassLoader loader = layer.findLoader("bananascript");
    List<ScriptEngineFactory> providers
        = collectAll(ServiceLoader.load(ScriptEngineFactory.class, loader));

    // should have at least 2 x bananascript + pearscript
    assertTrue(providers.size() >= 3);

    // first element should be the provider in the custom layer
    ScriptEngineFactory factory = providers.get(0);
    assertTrue(factory.getClass().getClassLoader() == loader);
    assertTrue(factory.getClass().getModule().getLayer() == layer);
    assertTrue(factory.getEngineName().equals("BananaScriptEngine"));

    // remainder should be the boot layer
    providers.remove(0);
    Set<String> names = providers.stream()
            .map(ScriptEngineFactory::getEngineName)
            .collect(Collectors.toSet());
    assertTrue(names.contains("BananaScriptEngine"));
    assertTrue(names.contains("PearScriptEngine"));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:ModulesTest.java

示例12: run

import java.util.ServiceLoader; //导入依赖的package包/类
@Override
public LoggingBackend run() {
    final Iterator<LoggerFinder> iterator =
        ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader())
        .iterator();
    if (iterator.hasNext()) {
        return LoggingBackend.CUSTOM; // Custom Logger Provider is registered
    }
    // No custom logger provider: we will be using the default
    // backend.
    final Iterator<DefaultLoggerFinder> iterator2 =
        ServiceLoader.loadInstalled(DefaultLoggerFinder.class)
        .iterator();
    if (iterator2.hasNext()) {
        // LoggingProviderImpl is registered. The default
        // implementation is java.util.logging
        String cname = System.getProperty("java.util.logging.config.class");
        String fname = System.getProperty("java.util.logging.config.file");
        return (cname != null || fname != null)
            ? LoggingBackend.JUL_WITH_CONFIG
            : LoggingBackend.JUL_DEFAULT;
    } else {
        // SimpleConsoleLogger is used
        return LoggingBackend.NONE;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:BootstrapLogger.java

示例13: getPlugins

import java.util.ServiceLoader; //导入依赖的package包/类
/**
 * The plugins accessible in the current context.
 *
 * @param pluginsLayer
 * @return The list of plugins.
 */
private static <T extends Plugin> List<T> getPlugins(Class<T> clazz, ModuleLayer pluginsLayer) {
    Objects.requireNonNull(pluginsLayer);
    List<T> factories = new ArrayList<>();
    try {
        Iterator<T> providers
                = ServiceLoader.load(pluginsLayer, clazz).iterator();
        while (providers.hasNext()) {
            factories.add(providers.next());
        }
        registeredPlugins.values().stream().forEach((fact) -> {
            if (clazz.isInstance(fact)) {
                @SuppressWarnings("unchecked")
                T trans = (T) fact;
                factories.add(trans);
            }
        });
        return factories;
    } catch (Exception ex) {
        throw new PluginException(ex);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:28,代码来源:PluginRepository.java

示例14: registerInstalledProviders

import java.util.ServiceLoader; //导入依赖的package包/类
private void registerInstalledProviders() {
    /*
      We need to load installed providers from the
      system classpath (typically the <code>lib/ext</code>
      directory in in the Java installation directory)
      in the privileged mode in order to
      be able read corresponding jar files even if
      file read capability is restricted (like the
      applet context case).
     */
    PrivilegedAction doRegistration =
        new PrivilegedAction() {
            public Object run() {
                Iterator categories = getCategories();
                while (categories.hasNext()) {
                    Class<IIOServiceProvider> c = (Class)categories.next();
                    for (IIOServiceProvider p : ServiceLoader.loadInstalled(c)) {
                        registerServiceProvider(p);
                    }
                }
                return this;
            }
        };

    AccessController.doPrivileged(doRegistration);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:27,代码来源:IIORegistry.java

示例15: testStreamOrder

import java.util.ServiceLoader; //导入依赖的package包/类
/**
 * Basic test of stream() to ensure that elements for providers in named
 * modules come before elements for providers in unnamed modules.
 */
@Test
public void testStreamOrder() {
    List<Class<?>> types = ServiceLoader.load(ScriptEngineFactory.class)
            .stream()
            .map(Provider::type)
            .collect(Collectors.toList());

    boolean foundUnnamed = false;
    for (Class<?> factoryClass : types) {
        if (factoryClass.getModule().isNamed()) {
            if (foundUnnamed) {
                assertTrue(false, "Named module element after unnamed");
            }
        } else {
            foundUnnamed = true;
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:23,代码来源:ModulesTest.java


注:本文中的java.util.ServiceLoader类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。