获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI

前言

在策略模式应用中,需要获取到策略接口的所有实现类,本文记录三种获取某接口所有实现类的方法,分别是利用Spring的ListableBeanFactory容器的getBeanNamesForType方法,利用Reflections工具进行反射扫描、利用SPI方式。
获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第1张图片

Spring的ListableBeanFactory容器的getBeanNamesForType方法

如果所有实现类已被Spring托管,因此可以通过容器getBeanNamesForType方法获取接口的所有实现类。
如果实现类同时实现了FactoryBean接口的话,getBeanNamesForType从容器中拿到的实现类为FactoryBean自身,beanName带"&"前缀,而不是其getObject方法所代理的类。
获取到ListableBeanFactory容器,有如下方法:

  • 实现BeanFactoryPostProcessor接口
  • 实现ApplicationContextAware接口
	/**
	 * Return the names of beans matching the given type (including subclasses),
	 * judging from either bean definitions or the value of {@code getObjectType}
	 * in the case of FactoryBeans.
	 * 

NOTE: This method introspects top-level beans only. It does not * check nested beans which might match the specified type as well. *

Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set, * which means that FactoryBeans will get initialized. If the object created by the * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked * (which doesn't require initialization of each FactoryBean). *

Does not consider any hierarchy this factory may participate in. * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors} * to include beans in ancestor factories too. *

Note: Does not ignore singleton beans that have been registered * by other means than bean definitions. *

Bean names returned by this method should always return bean names in the * order of definition in the backend configuration, as far as possible. * @param type the class or interface to match, or {@code null} for all bean names * @param includeNonSingletons whether to include prototype or scoped beans too * or just singletons (also applies to FactoryBeans) * @param allowEagerInit whether to initialize lazy-init singletons and * objects created by FactoryBeans (or by factory methods with a * "factory-bean" reference) for the type check. Note that FactoryBeans need to be * eagerly initialized to determine their type: So be aware that passing in "true" * for this flag will initialize FactoryBeans and "factory-bean" references. * @return the names of beans (or objects created by FactoryBeans) matching * the given object type (including subclasses), or an empty array if none * @see FactoryBean#getObjectType * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean) */ String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);

获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第2张图片
获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第3张图片
获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第4张图片

利用Reflections工具进行反射扫描

如果实现类都在相同包路径下,不想通过依赖Spring获取接口所有实现类,可以使用反射的方式扫描具体包路径获取所有实现类。

代码示例

maven依赖

        <dependency>
            <groupId>org.reflectionsgroupId>
            <artifactId>reflectionsartifactId>
            <version>0.9.11version>
        dependency>

代码示例

    /**
     * 通过反射扫描包路径的方式实现策略实现类的注册
     *
     * @throws Exception
     */
    public static void register() throws Exception {
        Reflections reflections = new Reflections(BuildLogsStrategy.class.getPackage().getName());
        Set<Class<? extends BuildLogsStrategy>> classes = reflections.getSubTypesOf(BuildLogsStrategy.class);

        for (Class clazz : classes) {
            BuildLogsStrategy strategy = (BuildLogsStrategy) clazz.newInstance();
            String methodOrClassName = strategy.getMethodOrClassName();
            STRATEGY_MAPS.put(methodOrClassName, strategy);
        }
    }

使用SPI获取接口所有实现类

以Motan的负载均衡算法实现类为例
获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第5张图片
按照SPI的使用方式,有两步操作:
1.在META-INF/Services路径下创建一个以接口全称为名的文件
2.文件内容为接口的所有实现类的全限定类名
获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第6张图片

代码示例

    @Test
    public void loadBalanceTest() {
        ExtensionLoader<LoadBalance> loader = ExtensionLoader.getExtensionLoader(LoadBalance.class);
        for (LoadBalance extension : loader.getExtensions(null)) {
            System.out.println(extension.getClass().getName());
        }
    }

测试代码运行结果:
获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI_第7张图片

其他方式

获取所有接口实现类,是按照某种分类规则对类进行分类需求的特例,通用的对类进行分组分类的方式,可以使用自定义注解+注解扫描器的方式,不需要实现相同的接口,不需要在同一个包路径下。

你可能感兴趣的:(开发经验分享,Spring)