DefaultListableBeanFactory
1.BeanFactory的三个亲子接口
上图展示的是BeanFactory
的三个儿子,这三个接口分别对BeanFactory进行了功能上的扩展
ListableBeanFactory
:对Bean信息、Bean定义信息进行查询操作- 涉及一个工具类:
_BeanFactoryUtils_
- 涉及一个工具类:
HierarchicalBeanFactory
:增加BeanFactory的父子关系的支持AutowireCapableBeanFactory
:提供创建Bean、应用后置处理器、自动注入等方法定义2.SingletonBeanRegistry
此类需要被
BeanFactory
的类实现,其作用是为单例Bean的获取和注册提供统一的操作行为3.AliasRegistry
3.1BeanDefinitionRegistry
继承
AliasRegistry
,定义了一系列关于BeanDefinition
的CRUD3.1SimpleAliasRegistry (实现类)
这是一个实现类,纯纯的就是对
AliasRegistry
定义的行为进行实现 ```java public class SimpleAliasRegistry implements AliasRegistry {/* Logger available to subclasses. / protected final Log logger = LogFactory.getLog(getClass());
/* 存放的是别名->规范的名 / private final Map
aliasMap = new ConcurrentHashMap<>(16);
@Override
public void registerAlias(String name, String alias) {
Assert.hasText(name, "'name' must not be empty");
Assert.hasText(alias, "'alias' must not be empty");
synchronized (this.aliasMap) {
if (alias.equals(name)) {
//name和alias相同时直接remove
this.aliasMap.remove(alias);
}
else {
String registeredName = this.aliasMap.get(alias);
if (registeredName != null) {
//若已经有相关的 alias啦
if (registeredName.equals(name)) {
// An existing alias - no need to re-register
return;
}
if (!allowAliasOverriding()) {
//不允许重复Alias
throw new IllegalStateException();
}
//日志
}
//别名循环 A->B->A
checkForAliasCircle(name, alias);
this.aliasMap.put(alias, name);
//日志
}
}
}
/**
* Determine whether alias overriding is allowed.
* <p>Default is {@code true}.
*/
protected boolean allowAliasOverriding() {
return true;
}
/**
* Determine whether the given name has the given alias registered.
* @param name the name to check
* @param alias the alias to look for
* @since 4.2.1
*/
public boolean hasAlias(String name, String alias) {
String registeredName = this.aliasMap.get(alias);
return ObjectUtils.nullSafeEquals(registeredName, name) || (registeredName != null
&& hasAlias(name, registeredName));
}
@Override
public void removeAlias(String alias) {
synchronized (this.aliasMap) {
String name = this.aliasMap.remove(alias);
//日志
}
}
@Override
public boolean isAlias(String name) {
return this.aliasMap.containsKey(name);
}
@Override
public String[] getAliases(String name) {
List<String> result = new ArrayList<>();
synchronized (this.aliasMap) {
retrieveAliases(name, result);
}
return StringUtils.toStringArray(result);
}
/**
* Transitively retrieve all aliases for the given name.
* @param name the target name to find aliases for
* @param result the resulting aliases list
*/
private void retrieveAliases(String name, List<String> result) {
this.aliasMap.forEach((alias, registeredName) -> {
if (registeredName.equals(name)) {
result.add(alias);
retrieveAliases(alias, result);
}
});
}
/**
* Resolve all alias target names and aliases registered in this
* registry, applying the given {@link StringValueResolver} to them.
* <p>The value resolver may for example resolve placeholders
* in target bean names and even in alias names.
* @param valueResolver the StringValueResolver to apply
*/
public void resolveAliases(StringValueResolver valueResolver) {
Assert.notNull(valueResolver, "StringValueResolver must not be null");
synchronized (this.aliasMap) {
Map<String, String> aliasCopy = new HashMap<>(this.aliasMap);
aliasCopy.forEach((alias, registeredName) -> {
String resolvedAlias = valueResolver.resolveStringValue(alias);
String resolvedName = valueResolver.resolveStringValue(registeredName);
if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) {
this.aliasMap.remove(alias);
}
else if (!resolvedAlias.equals(alias)) {
String existingName = this.aliasMap.get(resolvedAlias);
if (existingName != null) {
if (existingName.equals(resolvedName)) {
// Pointing to existing alias - just remove placeholder
this.aliasMap.remove(alias);
return;
}
throw new IllegalStateException(
"Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias +
"') for name '" + resolvedName + "': It is already registered for name '" +
registeredName + "'.");
}
checkForAliasCircle(resolvedName, resolvedAlias);
this.aliasMap.remove(alias);
this.aliasMap.put(resolvedAlias, resolvedName);
}
else if (!registeredName.equals(resolvedName)) {
this.aliasMap.put(alias, resolvedName);
}
});
}
}
/**
* Check whether the given name points back to the given alias as an alias
* in the other direction already, catching a circular reference upfront
* and throwing a corresponding IllegalStateException.
* @param name the candidate name
* @param alias the candidate alias
* @see #registerAlias
* @see #hasAlias
*/
protected void checkForAliasCircle(String name, String alias) {
if (hasAlias(alias, name)) {
throw new IllegalStateException(");
}
}
/**
* Determine the raw name, resolving aliases to canonical names.
* @param name the user-specified name
* @return the transformed name
*/
public String canonicalName(String name) {
String canonicalName = name;
// Handle aliasing...
String resolvedName;
do {
resolvedName = this.aliasMap.get(canonicalName);
if (resolvedName != null) {
canonicalName = resolvedName;
}
}
while (resolvedName != null);
return canonicalName;
}
}
<a name="Fr2Mc"></a>
## 4.DefaultSingletonBeanRegistry(实现类)
![image.png](https://cdn.nlark.com/yuque/0/2022/png/1609516/1655253809785-d6e9ec63-e45f-42c6-9236-c3ba203bebf5.png#clientId=u81e1cd3f-1762-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=321&id=u4c6ef407&margin=%5Bobject%20Object%5D&name=image.png&originHeight=214&originWidth=495&originalType=binary&ratio=1&rotation=0&showTitle=false&size=9245&status=done&style=none&taskId=ubf52d602-c776-437a-8687-282509bb146&title=&width=743)<br />作用:是对`SingletonBeanRegistry`的实现,对单例Bean进行管理
```java
/** Cache of singleton objects: bean name --> bean instance 缓存单例对象 */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name --> ObjectFactory 缓存单例对象工厂 */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name --> bean instance 缓存早期Bean */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** BeanNames集合(顺序按照注册顺序)*/
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
/** 正在创建的BeanName */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** Names of beans currently excluded from in creation checks */
private final Set<String> inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** List of suppressed Exceptions, available for associating related causes */
@Nullable
private Set<Exception> suppressedExceptions;
/** Flag that indicates whether we're currently within destroySingletons */
private boolean singletonsCurrentlyInDestruction = false;
/** Disposable 类型的 bean instances: bean name --> disposable instance */
private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
/** Map between containing bean names: bean name --> 依赖的beanName集合 Set of bean names that the bean contains */
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
/** Map between dependent bean names: bean name --> Set of dependent bean names */
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
/** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
4.1FactoryBeanRegistrySupport(抽象类)
- FactoryBean直接基础
DefaultSingletonBeanRegistry
,增加了对FactoryBean的特殊处理功能5.ConfigurableBeanFactory
提供了配置bean的方法5.1ConfigurableListableBeanFactory
在ConfigurableBeanFactory
的基础上把ListableBeanFactory
和AutowireCapableBeanFactory
进行了继承,新增了忽略类型及接口的方法定义
6.AbstractBeanFactory(抽象类)
抽象类,实现了ConfigurableBeanFactory
和继承FactoryBeanRegistrySupport
对子类公共的功能进行了实现
6.1AbstractAutowireCapableBeanFactory(抽象类)
抽象类,继承AbstractBeanFactory
同时实现了AutowireCapableBeanFactory
小结
DefaultListableBeanFactory
实现了ConfigurableListableBeanFactory
(这个接口拥有三个主要接口功能)和BeanDefinition
接口并继承了AbstractAutowireCapableBeanFactory
。XmlBeanFactory
是对DefaultListableBeanFactory
的扩展,添加了能够从XML文件中读取BeanDefinition
的功能,其实现类是XmlBeanDefinitionReader
@Deprecated
@SuppressWarnings({"serial", "all"})
public class XmlBeanFactory extends DefaultListableBeanFactory {
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
//....................
}
XmlBeanDefinitionReader
BeanDefinitionReader
EnvironmentCapable
ResourceLoader
类资源加载器,在AbstractBeanDefinitionReader
中引用
DocumentLoader
定义文件转换为Document
的功能,如将XML文件转换为Document
对象
BeanDefinitionDocumentReader
读取Document
对象中BenaDefinition
,是在方法中创建获取的
DefaultBeanDefinitionDocumentReader
实现了BeanDefinitionDocumentReader
BeanDefinitionParserDelegate
步骤描述
- 通过
ResourceLoader
将资源文件读取成为Resource
- 通过
DocumentLoader
将Resource
转换为Document
对象 - 通过
DefaultBeanDefinitionDocumentReader
对Document
对象进行解析,并使用BeanDefinitionParserDelegate
对Element
进行解析