BeanFactoryUtils
介绍
BeanFactoryUtils
是 Spring 框架中的一个实用工具类,提供了一些与 BeanFactory 相关的实用方法。它主要用于在 BeanFactory 中查找和管理 Bean,特别是在处理层次化 BeanFactory 时非常有用。
主要功能
BeanFactoryUtils
提供了以下几个主要功能:
查找 Bean:
- 在当前 BeanFactory 及其父 BeanFactory 中查找 Bean。
- 支持根据 Bean 名称、类型、别名等进行查找。
获取 Bean 名称列表:
- 获取当前 BeanFactory 及其父 BeanFactory 中所有 Bean 的名称列表。
获取 Bean 数量:
- 获取当前 BeanFactory 及其父 BeanFactory 中 Bean 的总数量。
判断 Bean 是否存在:
- 判断当前 BeanFactory 及其父 BeanFactory 中是否存在指定的 Bean。
源代码
package org.springframework.beans.factory;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Convenience methods operating on bean factories, in particular
* on the {@link ListableBeanFactory} interface.
*
* <p>Returns bean counts, bean names or bean instances,
* taking into account the nesting hierarchy of a bean factory
* (which the methods defined on the ListableBeanFactory interface don't,
* in contrast to the methods defined on the BeanFactory interface).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @since 04.07.2003
*/
public abstract class BeanFactoryUtils {
public static final String GENERATED_BEAN_NAME_SEPARATOR = "#";
private static final Map<String, String> transformedBeanNameCache = new ConcurrentHashMap<>();
public static boolean isFactoryDereference(@Nullable String name) {
return (name != null && name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
}
public static String transformedBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
return name;
}
return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
do {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
return beanName;
});
}
public static boolean isGeneratedBeanName(@Nullable String name) {
return (name != null && name.contains(GENERATED_BEAN_NAME_SEPARATOR));
}
public static String originalBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
int separatorIndex = name.indexOf(GENERATED_BEAN_NAME_SEPARATOR);
return (separatorIndex != -1 ? name.substring(0, separatorIndex) : name);
}
public static int countBeansIncludingAncestors(ListableBeanFactory lbf) {
return beanNamesIncludingAncestors(lbf).length;
}
public static String[] beanNamesIncludingAncestors(ListableBeanFactory lbf) {
return beanNamesForTypeIncludingAncestors(lbf, Object.class);
}
public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, ResolvableType type) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
String[] result = lbf.getBeanNamesForType(type);
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, Class<?> type) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
String[] result = lbf.getBeanNamesForType(type);
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
public static String[] beanNamesForTypeIncludingAncestors(
ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
public static String[] beanNamesForAnnotationIncludingAncestors(
ListableBeanFactory lbf, Class<? extends Annotation> annotationType) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
String[] result = lbf.getBeanNamesForAnnotation(annotationType);
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForAnnotationIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), annotationType);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
public static <T> Map<String, T> beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map<String, T> result = new LinkedHashMap<>(4);
result.putAll(lbf.getBeansOfType(type));
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
Map<String, T> parentResult = beansOfTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
parentResult.forEach((beanName, beanInstance) -> {
if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
result.put(beanName, beanInstance);
}
});
}
}
return result;
}
public static <T> Map<String, T> beansOfTypeIncludingAncestors(
ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map<String, T> result = new LinkedHashMap<>(4);
result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit));
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
Map<String, T> parentResult = beansOfTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
parentResult.forEach((beanName, beanInstance) -> {
if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
result.put(beanName, beanInstance);
}
});
}
}
return result;
}
public static <T> T beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
throws BeansException {
Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type);
return uniqueBean(type, beansOfType);
}
public static <T> T beanOfTypeIncludingAncestors(
ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type, includeNonSingletons, allowEagerInit);
return uniqueBean(type, beansOfType);
}
public static <T> T beanOfType(ListableBeanFactory lbf, Class<T> type) throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map<String, T> beansOfType = lbf.getBeansOfType(type);
return uniqueBean(type, beansOfType);
}
public static <T> T beanOfType(
ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map<String, T> beansOfType = lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit);
return uniqueBean(type, beansOfType);
}
private static String[] mergeNamesWithParent(String[] result, String[] parentResult, HierarchicalBeanFactory hbf) {
if (parentResult.length == 0) {
return result;
}
List<String> merged = new ArrayList<>(result.length + parentResult.length);
merged.addAll(Arrays.asList(result));
for (String beanName : parentResult) {
if (!merged.contains(beanName) && !hbf.containsLocalBean(beanName)) {
merged.add(beanName);
}
}
return StringUtils.toStringArray(merged);
}
private static <T> T uniqueBean(Class<T> type, Map<String, T> matchingBeans) {
int count = matchingBeans.size();
if (count == 1) {
return matchingBeans.values().iterator().next();
}
else if (count > 1) {
throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
}
else {
throw new NoSuchBeanDefinitionException(type);
}
}
}
主要方法
isFactoryDereference
判断给定的 Bean 名称是否是一个工厂 Bean 的引用。
public static boolean isFactoryDereference(@Nullable String name) {
return (name != null && name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
}
transformedBeanName
将工厂 Bean 的引用名称转换为实际的 Bean 名称。
public static String transformedBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
return name;
}
return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
do {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
return beanName;
});
}
isGeneratedBeanName
判断给定的 Bean 名称是否是一个生成的 Bean 名称。
public static boolean isFactoryDereference(@Nullable String name) {
return (name != null && name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
}
originalBeanName
获取生成的 Bean 名称的原始名称。
public static String originalBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
int separatorIndex = name.indexOf(GENERATED_BEAN_NAME_SEPARATOR);
return (separatorIndex != -1 ? name.substring(0, separatorIndex) : name);
}
beanNamesForTypeIncludingAncestors
获取当前 BeanFactory
及其父 BeanFactory
中所有指定类型的 Bean 名称列表。
public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, ResolvableType type) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
String[] result = lbf.getBeanNamesForType(type);
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
countBeansIncludingAncestors
获取当前 BeanFactory
及其父 BeanFactory
中 Bean 的总数量。
public static int countBeansIncludingAncestors(ListableBeanFactory lbf) {
return beanNamesIncludingAncestors(lbf).length;
}
beanNamesIncludingAncestors
获取当前 BeanFactory
及其父 BeanFactory
中所有 Bean 的名称列表。
public static String[] beanNamesIncludingAncestors(ListableBeanFactory lbf) {
return beanNamesForTypeIncludingAncestors(lbf, Object.class);
}
beansOfTypeIncludingAncestors
获取当前 BeanFactory
及其父 BeanFactory
中所有指定类型的 Bean 实例。
public static <T> Map<String, T> beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map<String, T> result = new LinkedHashMap<>(4);
result.putAll(lbf.getBeansOfType(type));
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
Map<String, T> parentResult = beansOfTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type);
parentResult.forEach((beanName, beanInstance) -> {
if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
result.put(beanName, beanInstance);
}
});
}
}
return result;
}
beanOfTypeIncludingAncestors
获取当前 BeanFactory
及其父 BeanFactory
中指定类型的单个 Bean 实例。
public static <T> T beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
throws BeansException {
Map<String, T> beansOfType = beansOfTypeIncludingAncestors(lbf, type);
return uniqueBean(type, beansOfType);
}
示例代码
DemoService
package com.yang.SpringTest.utils.beanFactoryUtils;
import org.springframework.stereotype.Component;
/**
* <p>BeanFactoryUtils学习 </p>
*
* @author By: chengxuyuanshitang <br>
* @Package: com.yang.SpringTest.utils.beanFactoryUtils <br>
* @CreateTime: 2024-11-20 14:41 <br>
*/
@Component
public class DemoService {
public void doSomething() {
System.out.println("DemoService 正在工作.");
}
}
AnotherDemoService
package com.yang.SpringTest.utils.beanFactoryUtils;
import org.springframework.stereotype.Component;
/**
* <p>BeanFactoryUtils学习 </p>
*
* @author By: chengxuyuanshitang <br>
* @Package: com.yang.SpringTest.utils.beanFactoryUtils <br>
* @CreateTime: 2024-11-20 14:41 <br>
*/
@Component
public class AnotherDemoService {
public void doSomething() {
System.out.println("AnotherDemoService 正在工作.");
}
}
BeanFactoryUtilsAppConfig
package com.yang.SpringTest.utils.beanFactoryUtils;
/**
* <p>BeanFactoryUtils学习 </p>
*
* @author By: chengxuyuanshitang <br>
* @Package: com.yang.SpringTest.utils.beanFactoryUtils <br>
* @CreateTime: 2024-11-20 14:42 <br>
*/
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.yang.SpringTest.utils.beanFactoryUtils")
public class BeanFactoryUtilsAppConfig {
}
BeanFactoryUtilsTest
package com.yang.SpringTest.utils.beanFactoryUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.beans.factory.BeanFactoryUtils;
import java.util.Arrays;
import java.util.Map;
/**
* <p>BeanFactoryUtils学习 </p>
*
* @author By: chengxuyuanshitang <br>
* @Package: com.yang.SpringTest.utils.beanFactoryUtils <br>
* @CreateTime: 2024-11-20 14:42 <br>
*/
@Slf4j
public class BeanFactoryUtilsTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BeanFactoryUtilsAppConfig.class);
ListableBeanFactory beanFactory = (ListableBeanFactory) context;
log.info("**************** IOC容器启动完成....");
// 获取所有 DemoService 类型的 Bean 名称
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, DemoService.class);
for (String beanName : beanNames) {
System.out.println("-------Bean name is : " + beanName);
}
// 获取所有 DemoService 类型的 Bean 实例
Map<String, DemoService> beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, DemoService.class);
for (Map.Entry<String, DemoService> entry : beansOfType.entrySet()) {
System.out.println("============Bean name is : " + entry.getKey());
entry.getValue().doSomething();
}
// 获取当前 BeanFactory 及其父 BeanFactory 中所有 Bean 的名称列表
String[] definitionList= BeanFactoryUtils.beanNamesIncludingAncestors(beanFactory);
Arrays.stream(definitionList).forEach((definitionName) -> System.out.println("**************** Bean name is " + definitionName));
// 获取 Bean 的总数量
int beanCount = BeanFactoryUtils.countBeansIncludingAncestors(beanFactory);
System.out.println("Total bean count is: " + beanCount);
}
}