前言
在策略模式应用中,需要获取到策略接口的所有实现类,本文记录三种获取某接口所有实现类的方法,分别是利用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.
* <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
* check nested beans which might match the specified type as well.
* <p>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).
* <p>Does not consider any hierarchy this factory may participate in.
* Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
* to include beans in ancestor factories too.
* <p>Note: Does <i>not</i> ignore singleton beans that have been registered
* by other means than bean definitions.
* <p>Bean names returned by this method should always return bean names <i>in the
* order of definition</i> 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 <i>lazy-init singletons</i> and
* <i>objects created by FactoryBeans</i> (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);
利用Reflections工具进行反射扫描
如果实现类都在相同包路径下,不想通过依赖Spring获取接口所有实现类,可以使用反射的方式扫描具体包路径获取所有实现类。
代码示例
maven依赖
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</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的负载均衡算法实现类为例
按照SPI的使用方式,有两步操作:
1.在META-INF/Services路径下创建一个以接口全称为名的文件
2.文件内容为接口的所有实现类的全限定类名
代码示例
@Test
public void loadBalanceTest() {
ExtensionLoader<LoadBalance> loader = ExtensionLoader.getExtensionLoader(LoadBalance.class);
for (LoadBalance extension : loader.getExtensions(null)) {
System.out.println(extension.getClass().getName());
}
}
测试代码运行结果:
其他方式
获取所有接口实现类,是按照某种分类规则对类进行分类需求的特例,通用的对类进行分组分类的方式,可以使用自定义注解+注解扫描器的方式,不需要实现相同的接口,不需要在同一个包路径下。