扩展点加载机制 - ExtensionLoader

更多干货

  • 分布式实战(干货)

  • spring cloud 实战(干货)

  • mybatis 实战(干货)

  • spring boot 实战(干货)

  • React 入门实战(干货)

  • 构建中小型互联网企业架构(干货)

  • python 学习持续更新

  • ElasticSearch 笔记

  • kafka storm 实战 (干货)

  • scala 学习持续更新

  • RPC

  • 深度学习

  • GO 语言 持续更新

  • Android 学习

  • nginx 相关文章

  • vue学习

扩展点加载机制 - ExtensionLoader

例子

        @Bean
        public ObjectSerializer objectSerializer() {
            return ExtensionLoader.getExtensionLoader(ObjectSerializer.class)
                    .getActivateExtension(env.getProperty("recover.serializer.support"));
        }
public final class ExtensionLoader {

    private Class type;

    private ExtensionLoader(final Class type) {
        this.type = type;
    }

    private static  boolean withExtensionAnnotation(final Class type) {
        return type.isAnnotationPresent(NickSPI.class);
    }

    /**
     * Gets extension loader.
     *
     * @param   the type parameter
     * @param type the type
     * @return the extension loader
     */
    public static  ExtensionLoader getExtensionLoader(final Class type) {
        if (type == null) {
            throw new NickException("type == null");
        }
        if (!type.isInterface()) {
            throw new NickException("Extension type(" + type + ") not interface!");
        }
        if (!withExtensionAnnotation(type)) {
            throw new NickException("type" + type.getName() + "not exist");
        }
        return new ExtensionLoader<>(type);
    }

    /**
     * Gets activate extension.
     *
     * @param value the value
     * @return the activate extension
     */
    public T getActivateExtension(final String value) {
        ServiceLoader loader = ServiceBootstrap.loadAll(type);
        return StreamSupport.stream(loader.spliterator(), false)
                .filter(e -> Objects.equals(e.getClass()
                        .getAnnotation(NickSPI.class).value(), value))
                .findFirst().orElseThrow(() -> new NickException("Please check your configuration"));
    }

}
public class ServiceBootstrap {

    /**
     * Load first s.
     *
     * @param    the type parameter
     * @param clazz the clazz
     * @return the s
     */
    public static  S loadFirst(final Class clazz) {
        final ServiceLoader loader = loadAll(clazz);
        final Iterator 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();
    }

    /**
     * Load all service loader.
     *
     * @param    the type parameter
     * @param clazz the clazz
     * @return the service loader
     */
    public static  ServiceLoader loadAll(final Class clazz) {
        return ServiceLoader.load(clazz);
    }

}

你可能感兴趣的:(java工具类)