一、getbeannamesfortype概述
/**
* Return the names of all beans of the specified type or subtypes, for the given bean factory.
* @param beanFactory the bean factory to find bean names in
* @param type the type that beans must match (as a {@code Class})
* @return the names of all beans of the specified type or subtypes (if any),
* or an empty array if none
* @since 3.0
*/
public static String[] getBeanNamesForType(ListableBeanFactory beanFactory, Class<?> type) {
return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, type);
}
getbeannamesfortype
是 Spring Framework 提供的一个方法,用于获取指定类及其子类在 IOC 容器中的所有 bean 的名称。该方法的基础调用方法是 beanNamesForTypeIncludingAncestors(beanFactory, type)
。
二、getbeannamesfortype 使用方式
1、通过 beanFactory 获取
ListableBeanFactory beanFactory = // 获取 beanFactory 实例
String[] beanNames = getBeanNamesForType(beanFactory, TestBean.class);
需要理解的是 getBeanNamesForType
方法需要的参数是 ListableBeanFactory
和 Class<?>
类型的 type
。不过要获得 ListableBeanFactory
对象,可以通过多种方式。
比如通过 FileSystemXmlApplicationContext
、ClassPathXmlApplicationContext
、AnnotationConfigApplicationContext
来获取 beanFactory
实例。
2、使用继承关系
String[] beanNames = getBeanNamesForType(beanFactory, ParentTestBean.class);
getBeanNamesForType
方法同时支持查询某个类的所有子类的 bean 名称。这是基于某个 bean 定义按继承关系组织在 IOC 中的情况。这种情况下,查询 ParentTestBean
的子类 TestBean
的 bean 名称时会返回相应的结果。
3、使用泛型类型
String[] beanNames = getBeanNamesForType(beanFactory, new ParameterizedTypeReference<Map<String, List<String>>>() {});
getBeanNamesForType
方法同时支持查询复杂泛型类型的 bean。可以通过 new ParameterizedTypeReference
来获取泛型类,如上述代码中的 Map<String, List<String>>
。
三、getbeannamesfortype 的返回值
1、返回值为所有 bean 名称数组
String[] beanNames = getBeanNamesForType(beanFactory, TestBean.class);
当 IOC 中有多个符合类型的 bean 时,getBeanNamesForType
方法返回所有 bean 名称的数组。
2、返回值为空数组
String[] beanNames = getBeanNamesForType(beanFactory, NonExistType.class);
当 IOC 中不存在某类型的 bean 时,getBeanNamesForType
方法返回一个空数组。
3、返回值为根据父子继承关系组织的 bean 名称数组
@Test
public void testGetBeanNamesForTypeWithHierarchy() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions("com/example/demo/spring.xml");
String[] beanNames = getBeanNamesForType(beanFactory, Animal.class);
assertEquals(2, beanNames.length);
assertEquals("dog", beanNames[0]);
assertEquals("cat", beanNames[1]);
}
当 IOC 容器中使用父子继承关系组织 bean 定义时,getBeanNamesForType
方法返回的 bean 名称数组按照继承关系从上到下进行排序。
四、总结
getbeannamesfortype
是 Spring Framework 中的一个常用工具方法,用于查询 IOC 容器中符合条件的 bean 的名称,并且支持查询类型及其子类型、泛型类型相关的 bean 名称。同时,该方法返回的 bean 名称数组可以用于进一步操作,比如通过 beanFactory
获取到 bean 的实例。