获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI 您所在的位置:网站首页 java查看接口的实现类 获取接口所有实现类的三种方式:Spring的ListableBeanFactory容器的getBeanNamesForType方法、利用Reflections工具进行反射扫描、使用SPI

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

2023-10-17 05:24| 来源: 网络整理| 查看: 265

前言

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

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有