BeanDefinitionRegistry
在闡釋BeanDefinitionRegistry
之前迟蜜,我們有必要簡單提一下BeanDefinition
。BeanDefinition
是spring容器中bean的定義荡短,這些定義可以是xml配置丐枉,可以是注解配置,還可以是別的掘托。
BeanDefinitionRegistry
是一個(gè)接口瘦锹,中文名為BeanDefinition注冊(cè)器
,繼承了AliasRegistry
接口,同時(shí)增加了對(duì)BeanDefinition
的管理弯院。
因此噩峦,我們可以說,這個(gè)接口包含以下幾方面的功能:
-
BeanDefinition
管理的功能 - 包含對(duì)別名管理的功能
public interface BeanDefinitionRegistry extends AliasRegistry {
/**
* 注冊(cè)BeanDefinition
* Register a new bean definition with this registry.
* Must support RootBeanDefinition and ChildBeanDefinition.
* @param beanName the name of the bean instance to register
* @param beanDefinition definition of the bean instance to register
* @throws BeanDefinitionStoreException if the BeanDefinition is invalid
* @throws BeanDefinitionOverrideException if there is already a BeanDefinition
* for the specified bean name and we are not allowed to override it
* @see GenericBeanDefinition
* @see RootBeanDefinition
* @see ChildBeanDefinition
*/
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
/**
* 移除BeanDefinition
* Remove the BeanDefinition for the given name.
* @param beanName the name of the bean instance to register
* @throws NoSuchBeanDefinitionException if there is no such bean definition
*/
void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
/**
* 根據(jù)bean名稱獲取BeanDefinition
* Return the BeanDefinition for the given bean name.
* @param beanName name of the bean to find a definition for
* @return the BeanDefinition for the given name (never {@code null})
* @throws NoSuchBeanDefinitionException if there is no such bean definition
*/
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
/**
* 判斷是否包含bean名稱
* Check if this registry contains a bean definition with the given name.
* @param beanName the name of the bean to look for
* @return if this registry contains a bean definition with the given name
*/
boolean containsBeanDefinition(String beanName);
/**
* 獲取BeanDefinition的所有名稱數(shù)組
* Return the names of all beans defined in this registry.
* @return the names of all beans defined in this registry,
* or an empty array if none defined
*/
String[] getBeanDefinitionNames();
/**
* 獲取BeanDefinition的數(shù)量
* Return the number of beans defined in the registry.
* @return the number of beans defined in the registry
*/
int getBeanDefinitionCount();
/**
* 判斷beanName對(duì)應(yīng)的BeanDefinition是否被使用了
* Determine whether the given bean name is already in use within this registry,
* i.e. whether there is a local bean or alias registered under this name.
* @param beanName the name to check
* @return whether the given bean name is already in use
*/
boolean isBeanNameInUse(String beanName);
}
DefaultListableBeanFactory中的實(shí)現(xiàn)
DefaultListableBeanFactory
是BeanFactory的具體實(shí)現(xiàn)抽兆,內(nèi)容繁多且負(fù)責(zé)识补,這兒僅僅分析實(shí)現(xiàn)BeanDefinitionRegistry
接口的那些方法。
涉及到的字段信息
// BeanDefinition容器
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
// BeanDefinition名稱列表
/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
// 手動(dòng)單例名稱列表
/** List of names of manually registered singletons, in registration order. */
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
// 凍結(jié)名稱列表
/** Cached array of bean definition names in case of frozen configuration. */
@Nullable
private volatile String[] frozenBeanDefinitionNames;
// 凍結(jié)開關(guān)辫红,默認(rèn)關(guān)閉
/** Whether bean definition metadata may be cached for all beans. */
private volatile boolean configurationFrozen = false;
registerBeanDefinition
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
// beanName不允許為空凭涂,beanDefinition不允許為null
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
// 如果是AbstractBeanDefinition類型,則需要調(diào)用`validate()`校驗(yàn)一下正確性
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
// 嘗試從BeanDefinition容器中查找
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
// BeanDefinition容器中存在贴妻,則做了以下事情:
// 1. 如果不允許重復(fù)注冊(cè)切油,則拋出異常
// 2. 條件滿足的情況下,記錄一帕拉日志
// 3. 注冊(cè)到BeanDefinition容器
if (existingDefinition != null) {
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
else if (!beanDefinition.equals(existingDefinition)) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
// BeanDefinition容器中不存在
// 1. 如果bean創(chuàng)建已經(jīng)開始名惩,則需要在鎖環(huán)境下完成注冊(cè)操作
// 2. 如果bean創(chuàng)建還未開始澎胡,則不需要在所環(huán)境下操作,因?yàn)檫@個(gè)時(shí)候所有的操作都是在一個(gè)線程內(nèi)完成
// 3. 清空凍結(jié)名稱列表娩鹉,目的是為了后續(xù)查找方便
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
removeManualSingletonName(beanName);
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null;
}
// 如果BeanDefinition容器中存在攻谁,或者當(dāng)前BeanDefinition是一個(gè)單例定義,則需要重置BeanDefinition
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}
resetBeanDefinition
/**
* 重置BeanDefinition弯予,包括beanName被移除或替換的場(chǎng)景戚宦。
* Reset all bean definition caches for the given bean,
* including the caches of beans that are derived from it.
* <p>Called after an existing bean definition has been replaced or removed,
* triggering {@link #clearMergedBeanDefinition}, {@link #destroySingleton}
* and {@link MergedBeanDefinitionPostProcessor#resetBeanDefinition} on the
* given bean and on all bean definitions that have the given bean as parent.
* @param beanName the name of the bean to reset
* @see #registerBeanDefinition
* @see #removeBeanDefinition
*/
protected void resetBeanDefinition(String beanName) {
// Remove the merged bean definition for the given bean, if already created.
// 清除合并的BeanDefinition
clearMergedBeanDefinition(beanName);
// Remove corresponding bean from singleton cache, if any. Shouldn't usually
// be necessary, rather just meant for overriding a context's default beans
// (e.g. the default StaticMessageSource in a StaticApplicationContext).
// 銷毀單例
destroySingleton(beanName);
// Notify all post-processors that the specified bean definition has been reset.
// 調(diào)用MergedBeanDefinitionPostProcessor進(jìn)行回調(diào)處理
for (BeanPostProcessor processor : getBeanPostProcessors()) {
if (processor instanceof MergedBeanDefinitionPostProcessor) {
((MergedBeanDefinitionPostProcessor) processor).resetBeanDefinition(beanName);
}
}
// Reset all bean definitions that have the given bean as parent (recursively).
for (String bdName : this.beanDefinitionNames) {
if (!beanName.equals(bdName)) {
BeanDefinition bd = this.beanDefinitionMap.get(bdName);
// Ensure bd is non-null due to potential concurrent modification
// of the beanDefinitionMap.
// 父名稱和當(dāng)前名稱相同的情況下,需要遞歸調(diào)用此方法
if (bd != null && beanName.equals(bd.getParentName())) {
resetBeanDefinition(bdName);
}
}
}
}
removeBeanDefinition
public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
Assert.hasText(beanName, "'beanName' must not be empty");
// 移除不存在的BeanDefinition锈嫩,會(huì)拋出異常
BeanDefinition bd = this.beanDefinitionMap.remove(beanName);
if (bd == null) {
if (logger.isTraceEnabled()) {
logger.trace("No bean named '" + beanName + "' found in " + this);
}
throw new NoSuchBeanDefinitionException(beanName);
}
// 和注冊(cè)邏輯一樣受楼,Bean創(chuàng)建開始了,則需要在鎖環(huán)境下進(jìn)行移除操作呼寸,同時(shí)額外執(zhí)行以下操作:
// 1. 清空凍結(jié)名稱列表
// 2. 重置BeanDefinition
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames);
updatedDefinitions.remove(beanName);
this.beanDefinitionNames = updatedDefinitions;
}
}
else {
// Still in startup registration phase
this.beanDefinitionNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
resetBeanDefinition(beanName);
}
getBeanDefinition && containsBeanDefinition && getBeanDefinitionCount
很簡單艳汽!
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
if (logger.isTraceEnabled()) {
logger.trace("No bean named '" + beanName + "' found in " + this);
}
throw new NoSuchBeanDefinitionException(beanName);
}
return bd;
}
public boolean containsBeanDefinition(String beanName) {
Assert.notNull(beanName, "Bean name must not be null");
return this.beanDefinitionMap.containsKey(beanName);
}
public int getBeanDefinitionCount() {
return this.beanDefinitionMap.size();
}
getBeanDefinitionNames
首先從frozenBeanDefinitionNames
獲取,如果為null对雪,再從beanDefinitionNames
獲取河狐。
【注意】:為了線程安全,這兒使用了數(shù)組的clone()
操作慌植。
public String[] getBeanDefinitionNames() {
String[] frozenNames = this.frozenBeanDefinitionNames;
if (frozenNames != null) {
return frozenNames.clone();
}
else {
return StringUtils.toStringArray(this.beanDefinitionNames);
}
}
isBeanNameInUse
這個(gè)方法在AbstractBeanFactory
類里面甚牲。beanName是否在使用,有3種情況:
- 是一個(gè)別名
- 是一個(gè)本地Bean的名稱
- 通過這個(gè)名字創(chuàng)建了一個(gè)內(nèi)部bean(也叫依賴bean)
public boolean isBeanNameInUse(String beanName) {
return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
}
總結(jié)
至此蝶柿,我們粗略地對(duì)BeanDefinitionRegistry
及其實(shí)現(xiàn)DefaultListableBeanFactory
進(jìn)行了分析丈钙。相對(duì)來說,比較簡單交汤,主要是對(duì)ConcurrentHashMap
這種集合對(duì)象進(jìn)行增刪改查操作雏赦。