Spring BeanFactory工厂使用教程
首先,我们想要知道一个接口有哪些功能,就必须要看这个接口的源代码,在idea中,选中这个接口Ctrl+F12,来查看这个接口里面有哪些方法:
表面上来看,功能其实很少,查看源码及其方法、功能
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
public interface BeanFactory {
// factoryBean 的转义标识符。
String FACTORY_BEAN_PREFIX = "&";
// 根据 name 从容器中拿对应的 bean。
Object getBean(String name) throws BeansException;
// 根据 name 和 type 从容器中拿对应的 bean,要对 bean 的类型做校验。
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
// 在容器中能否找到与 name 匹配的 bean 或者 beanDefinition。
boolean containsBean(String name);
// 判断 name 对对应的 bean 是不是 单例。
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
// 判断 name 对应的 bean 与指定的类型是否匹配。
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws
NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws
NoSuchBeanDefinitionException;
//根据 name 获取对应的 bean 的类型。
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
// 根据 name 获取对应 bean 的 别名。
String[] getAliases(String name);
}
BeanFactory表面上来看只有 getBean有点用,实际上我们不能只光看它接口,还要看它的实现类,实际上控制反转、基本的依赖注入、直至 Bean 的生命周期的各种功能,都由它的实现类提供
- HierarchicalBeanFactory:提供父容器的访问功能
- ListableBeanFactory:提供了批量获取Bean的方法
- AutowireCapableBeanFactory:在BeanFactory基础上实现对已存在实例的管理
- ConfigurableBeanFactory:主要单例bean的注册,生成实例,以及统计单例bean
- ConfigurableListableBeanFactory:继承了上述的所有接口,增加了其他功能:比如类加载器,类型转化,属性编辑器,BeanPostProcessor,作用域,bean定义,处理bean依赖关系, bean如何销毁…
- 实现类DefaultListableBeanFactory:实现了ConfigurableListableBeanFactory,注册BeanDefinition,实现上述BeanFactory所有功能
来看一下DefaultListableBeanFactory的继承关系图:
可以看到,BeanFactory只是它实现的很少一部分,除了BeanFactory提供的getBean,还有其他方法,所以我们不能光看一个接口,还要看它的具体实现类
在这里我们就只看它的DefaultSingletonBeanRegistry接口中的单例对象,这个为大家比较熟悉的,来看源码:
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
private final Set<String> inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
@Nullable
private Set<Exception> suppressedExceptions;
private boolean singletonsCurrentlyInDestruction = false;
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
//断言beanName是否为空
Assert.notNull(beanName, "Bean name must not be null");
//断言singletonObject是否为空
Assert.notNull(singletonObject, "Singleton object must not be null");
synchronized (this.singletonObjects) {
//从一级缓存中通过beanName拿取Bean
Object oldObject = this.singletonObjects.get(beanName);
//一级缓存中存在了,抛出IllegalStateException
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
//如果不存在,将singletonObject添加到一级缓存
addSingleton(beanName, singletonObject);
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
//将singletonObject添加到一级缓存中,同时移除二级、三级缓存、并标记当前Bean已注册
this.singletonObjects.put(beanName, singletonObject);
//移除三级缓存
this.singletonFactories.remove(beanName);
//移除二级缓存
this.earlySingletonObjects.remove(beanName);
//标记当前Bean已被注册
this.registeredSingletons.add(beanName);
}
}
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
//断言singletonFactory不为空
Assert.notNull(singletonFactory, "Singleton factory must not be null");
//同步加锁
synchronized (this.singletonObjects) {
//单例缓存池中没有包含当前的bean
if (!this.singletonObjects.containsKey(beanName)) {
//加入到三级缓存中,,,,,暴露早期对象用于解决循环依赖
this.singletonFactories.put(beanName, singletonFactory);
//从二级缓存中移除
this.earlySingletonObjects.remove(beanName);
//标记当前Bean已经被注册过
this.registeredSingletons.add(beanName);
}
}
}
@Override
@Nullable
public Object getSingleton(String beanName) {
//在这里 系统一般是允许早期对象引用的 allowEarlyReference通过这个参数可以控制解决循环依赖
return getSingleton(beanName, true);
}
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
Object singletonObject = this.singletonObjects.get(beanName);
//如果一级缓存为空,并且标记正在创建
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
//一级缓存中没拿到
if (singletonObject == null) {
//尝试从二级缓存中去拿
singletonObject = this.earlySingletonObjects.get(beanName);
//二级缓存还是空
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
//三级缓存中获取的对象不为空
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
//把早期对象放置在二级缓存,
this.earlySingletonObjects.put(beanName, singletonObject);
//ObjectFactory 包装对象从三级缓存中删除掉
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
//返回这个Bean
return singletonObject;
}
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
//断言beanName不为空
Assert.notNull(beanName, "Bean name must not be null");
//同步加锁
synchronized (this.singletonObjects) {
//尝试从一级缓存池中获取对象
Object singletonObject = this.singletonObjects.get(beanName);
//从一级缓存中没拿到
if (singletonObject == null) {
//当前是否是正在销毁,是的话抛出BeanCreationNotAllowedException异常
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
//判断是否已启用Debug调试模式
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
//标记是否为新创建的单例Bean
boolean newSingleton = false;
//标记是否记录抑制异常
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
//如果为空,创建抑制异常集合
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 初始化 bean
// 这个过程其实是调用 createBean() 方法
singletonObject = singletonFactory.getObject();
//标记这个Bean是新创建的
newSingleton = true;
} catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
//
//在此期间是否隐式创建了单例对象 -> 如果是,则继续处理它,因为异常指该状态。
singletonObject = this.singletonObjects.get(beanName);
//一级缓存中没有,抛出异常
if (singletonObject == null) {
throw ex;
}
} catch (BeanCreationException ex) {
//记录抑制异常
if (recordSuppressedExceptions) {
//遍历抑制异常集合,添加相关原因
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
//记录抑制异常集合置空,复用
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//后置处理
//主要做的事情就是把singletonsCurrentlyInCreation标记正在创建的bean从集合中移除
afterSingletonCreation(beanName);
}
//是新建的单例Bean,添加到一级缓存中去
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
//返回单例Bean
return singletonObject;
}
}
protected void onSuppressedException(Exception ex) {
synchronized (this.singletonObjects) {
//抑制异常集合不为空,且小于SUPPRESSED_EXCEPTIONS_LIMIT最大限制
if (this.suppressedExceptions != null && this.suppressedExceptions.size() < SUPPRESSED_EXCEPTIONS_LIMIT) {
//向抑制集合中添加异常
this.suppressedExceptions.add(ex);
}
}
}
protected void removeSingleton(String beanName) {
//同步加锁
synchronized (this.singletonObjects) {
//从一级缓存中移除
this.singletonObjects.remove(beanName);
//从三级缓存中移除
this.singletonFactories.remove(beanName);
//从二级缓存中移除
this.earlySingletonObjects.remove(beanName);
//从Bean注册标记集合中移除
this.registeredSingletons.remove(beanName);
}
}
@Override
public boolean containsSingleton(String beanName) {
//判断一级缓存中是否存在该Bean
return this.singletonObjects.containsKey(beanName);
}
@Override
public String[] getSingletonNames() {
synchronized (this.singletonObjects) {
//获取已注册的单例Bean名字的集合
return StringUtils.toStringArray(this.registeredSingletons);
}
}
@Override
public int getSingletonCount() {
synchronized (this.singletonObjects) {
//获取已注册单例Bean实例的个数
return this.registeredSingletons.size();
}
}
public void setCurrentlyInCreation(String beanName, boolean inCreation) {
//断言Bean不为空
Assert.notNull(beanName, "Bean name must not be null");
//如果未标记,将beanName加到inCreationCheckExclusions集合中,已标记则移除
if (!inCreation) {
this.inCreationCheckExclusions.add(beanName);
} else {
this.inCreationCheckExclusions.remove(beanName);
}
}
public boolean isCurrentlyInCreation(String beanName) {
Assert.notNull(beanName, "Bean name must not be null");
return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
}
protected boolean isActuallyInCreation(String beanName) {
return isSingletonCurrentlyInCreation(beanName);
}
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
public void registerContainedBean(String containedBeanName, String containingBeanName) {
synchronized (this.containedBeanMap) {
Set<String> containedBeans =
this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
if (!containedBeans.add(containedBeanName)) {
return;
}
}
registerDependentBean(containedBeanName, containingBeanName);
}
public void registerDependentBean(String beanName, String dependentBeanName) {
//获取原始的beanName
String canonicalName = canonicalName(beanName);
// 添加 <canonicalName, <dependentBeanName>> 到 dependentBeanMap 中
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
// 添加 <dependentBeanName, <canonicalName>> 到 dependenciesForBeanMap 中
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
//判断指定的 bean 是否依赖于 dependentBeanName
protected boolean isDependent(String beanName, String dependentBeanName) {
synchronized (this.dependentBeanMap) {
return isDependent(beanName, dependentBeanName, null);
}
}
//判断指定的 bean 是否依赖于 dependentBeanName
private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
// alreadySeen 已经检测的依赖 bean
if (alreadySeen != null && alreadySeen.contains(beanName)) {
return false;
}
// 获取原始 beanName
String canonicalName = canonicalName(beanName);
//获取创建当前bean 所依赖的bean的名称集合
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
//不依赖任何前置Bean 直接返回
if (dependentBeans == null) {
return false;
}
// 存在,则证明存在已经注册的依赖
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
// 递归检测依赖
for (String transitiveDependency : dependentBeans) {
if (alreadySeen == null) {
alreadySeen = new HashSet<>();
}
// 添加到 alreadySeen 中
alreadySeen.add(beanName);
//递归检查依赖
if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
return true;
}
}
return false;
}
//判断beanName是否注册为依赖Bean
protected boolean hasDependentBean(String beanName) {
return this.dependentBeanMap.containsKey(beanName);
}
public String[] getDependentBeans(String beanName) {
//Bean依赖集合
Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
if (dependentBeans == null) {
return new String[0];
}
synchronized (this.dependentBeanMap) {
return StringUtils.toStringArray(dependentBeans);
}
}
public String[] getDependenciesForBean(String beanName) {
Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
if (dependenciesForBean == null) {
return new String[0];
}
synchronized (this.dependenciesForBeanMap) {
return StringUtils.toStringArray(dependenciesForBean);
}
}
public void destroySingletons() {
if (logger.isTraceEnabled()) {
logger.trace("Destroying singletons in " + this);
}
//标记为正在销毁
synchronized (this.singletonObjects) {
this.singletonsCurrentlyInDestruction = true;
}
String[] disposableBeanNames;
//获取需要销毁的Bean集合
synchronized (this.disposableBeans) {
disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
}
//循环校徽单例Bean
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
// 清空依赖和映射关系缓存
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
// 清理Bean的一级二级三级缓存
clearSingletonCache();
}
protected void clearSingletonCache() {
synchronized (this.singletonObjects) {
this.singletonObjects.clear();
this.singletonFactories.clear();
this.earlySingletonObjects.clear();
this.registeredSingletons.clear();
this.singletonsCurrentlyInDestruction = false;
}
}
public void destroySingleton(String beanName) {
// Remove a registered singleton of the given name, if any.
//从缓存中移除当前bean的相关信息,由于不知道在哪里发生异常,所以我们把跟当前bean的所有缓存记录都清除
removeSingleton(beanName);
// Destroy the corresponding DisposableBean instance.
//创建一个变量用于接受 实现了DisposableBean接口的对象变量
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
//进行bean的销毁
destroyBean(beanName, disposableBean);
}
protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
// Trigger destruction of dependent beans first...
// 销毁dependentBeanMap中保存的是当前bean和依赖bean之间的映射
Set<String> dependencies;
synchronized (this.dependentBeanMap) {
// Within full synchronization in order to guarantee a disconnected Set
//把当前创建dependon 依赖的bean从缓存中移除并且返回处理
dependencies = this.dependentBeanMap.remove(beanName);
}
//如果bean依赖不为空
if (dependencies != null) {
if (logger.isTraceEnabled()) {
logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
}
//递归销毁bean
for (String dependentBeanName : dependencies) {
destroySingleton(dependentBeanName);
}
}
// Actually destroy the bean now...
//真正的调用bean的destory()方法
if (bean != null) {
try {
bean.destroy();
} catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
}
}
}
// 删除bean的属性关系的映射
Set<String> containedBeans;
synchronized (this.containedBeanMap) {
// Within full synchronization in order to guarantee a disconnected Set
containedBeans = this.containedBeanMap.remove(beanName);
}
if (containedBeans != null) {
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}
// Remove destroyed bean from other beans' dependencies.
//销毁dependentBeanMap 中 Bean的依赖
synchronized (this.dependentBeanMap) {
for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Set<String>> entry = it.next();
Set<String> dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) {
it.remove();
}
}
}
// Remove destroyed bean's prepared dependency information.
//从dependenciesForBeanMap集合移除
this.dependenciesForBeanMap.remove(beanName);
}
@Override
public final Object getSingletonMutex() {
return this.singletonObjects;
}
}
它的方法大多为私有的,可以通过debug和反射,在这里我们通过反射来获取私有的成员变量:
// DefaultSingletonBeanRegistry类管理所有的单例对象
//获取所有的私有成员变量
Field singletonObjects =
DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
//允许可以访问私有成员变量
singletonObjects.setAccessible(true);
//通过反射获取
//获取beanFactory
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//反射调用,获取beanFactory的属性
Map<String, Object> map = (Map<String, Object>) singletonObjects.get(beanFactory);
//过滤,获取component相关的
map.entrySet().stream().filter(e -> e.getKey().startsWith("component"))
.forEach(e -> {
System.out.println(e.getKey() + "=" + e.getValue());
});
总结:
BeanFactory 能干点啥?
- 表面上只有 getBean
- 实际上控制反转、基本的依赖注入、直至 Bean 的生命周期的各种功能,都由它的实现类提供
- 例子中通过反射查看了它的成员变量 singletonObjects,内部包含了所有的单例 bean
到此这篇关于Spring BeanFactory工厂使用教程的文章就介绍到这了,更多相关Spring BeanFactory内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341