前言
在Spring IOC機(jī)制里面哈垢,BeanFactory
是其中最最核心的一個(gè)組件凯旭。之所以說(shuō)它是一個(gè)組件属提,而不是一個(gè)類,是因?yàn)樗哂邢鄬?duì)較復(fù)雜的繼承關(guān)系病往,同時(shí)將工廠設(shè)計(jì)模式的精髓發(fā)揮得玲離盡致捣染。我們平時(shí)使用Spring IOC的時(shí)候,絕大多數(shù)情況是使用ApplicationContext
及其子類停巷,而非BeanFactory
耍攘。而ApplicationContext
的實(shí)現(xiàn)類,內(nèi)部仍然是通過(guò)引用BeanFactory
實(shí)例的方式來(lái)增強(qiáng)其bean管理的特性畔勤。
因此蕾各,在本文中,我們將從BeanFactory
的繼承關(guān)系出發(fā)硼被,詳細(xì)分析BeanFactory
作為bean管理容器可能存在的功能示损。
繼承關(guān)系圖
首先,我們來(lái)看看繼承關(guān)系嚷硫,如下圖所示检访。
紅框內(nèi)的類,正是BeanFactory
涉及到的繼承的基礎(chǔ)仔掸。每一個(gè)接口都定義了一部分功能脆贵,而每一個(gè)類都基于接口實(shí)現(xiàn)了一部分功能邏輯。而最核心的類在于DefaultListableBeanFactory
起暮,它是BeanFactory
的最終實(shí)現(xiàn)類卖氨。
類名 | 作用 |
---|---|
Beanfactory | 定義了Bean的一些查詢操作,包括根據(jù)名稱或類型獲取Bean,判斷Bean是否存在等筒捺。 |
HierarchicalBeanFactory | 定義了BeanFactory 的可繼承特性柏腻,包括獲取BeanFactory 的父BeanFactory 等。 |
ListableBeanFactory | 定義了BeanDefinition 的查詢操作系吭,以及根據(jù)Bean的類型獲取多個(gè)Bean實(shí)現(xiàn)的操作等五嫂。 |
ConfigurableBeanFactory | 意為可配置的BeanFactory ,可以對(duì)BeanFactory 進(jìn)行更新操作肯尺,包括各類注冊(cè)器的注冊(cè)沃缘,設(shè)置 父BeanFactory ,Bean的銷毀操作等则吟。 |
AutowireCapableBeanFactory | 可自動(dòng)裝配的BeanFactory 槐臀,我們可以手動(dòng)注冊(cè)一些Bean。該接口盡管不是很常用氓仲,但有些場(chǎng)景卻必須要使用到它水慨,我們后續(xù)會(huì)具體分析使用場(chǎng)景。 |
ConfigurableListableBeanFactory | 在ConfigurableBeanFactory 之上做了一些增強(qiáng)寨昙,包括BeanFactory 的分析讥巡,BeanDefinition 的修改,以及預(yù)實(shí)例化單例Bean等操作舔哪。 |
AbstractBeanFactory |
Beanfactory 欢顷、HierarchicalBeanFactory 和ConfigurableBeanFactory 的基本實(shí)現(xiàn) |
AbstractAutowireCapableBeanFactory |
AutowireCapableBeanFactory 的基本實(shí)現(xiàn) |
DefaultListableBeanFactory |
ListableBeanFactory 、ConfigurableListableBeanFactory 的基本實(shí)現(xiàn) |
BeanFactory
public interface BeanFactory {
/**
* 工廠Bean在BeanFactory中的bean名稱前綴捉蚤,用于區(qū)別于由其創(chuàng)建的Bean抬驴。
* Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the
* Singleton or Prototype design pattern. Callers may retain references to
* returned objects in the case of Singleton beans.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no bean with the specified name
* @throws BeansException if the bean could not be obtained
*/
String FACTORY_BEAN_PREFIX = "&";
/**
* 根據(jù)bean名稱,獲取bean實(shí)例缆巧。
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
* safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
* required type. This means that ClassCastException can't be thrown on casting
* the result correctly, as can happen with {@link #getBean(String)}.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
*/
Object getBean(String name) throws BeansException;
/**
* 根據(jù)bean名稱布持,獲取特定類型的bean實(shí)例,當(dāng)類型不匹配時(shí)拋出異常陕悬。
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
/**
* 根據(jù)bean名稱题暖,獲取bean實(shí)例,并且創(chuàng)建bean的時(shí)候需要根據(jù)args參數(shù)進(jìn)行創(chuàng)建捉超。
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
Object getBean(String name, Object... args) throws BeansException;
/**
* 根據(jù)bean的類型胧卤,獲取bean實(shí)例。
* 當(dāng)未獲取到bean實(shí)例拼岳,或者獲取到的bean實(shí)例數(shù)超過(guò)1個(gè)枝誊,則拋出異常。
* Return the bean instance that uniquely matches the given object type, if any.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the single bean matching the required type
* @throws NoSuchBeanDefinitionException if no bean of the given type was found
* @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
* @throws BeansException if the bean could not be created
* @since 3.0
* @see ListableBeanFactory
*/
<T> T getBean(Class<T> requiredType) throws BeansException;
/**
* 根據(jù)bean的類型惜纸,獲取bean實(shí)例叶撒,并且創(chuàng)建bean的時(shí)候需要根據(jù)args參數(shù)進(jìn)行創(chuàng)建绝骚。
* 當(dāng)未獲取到bean實(shí)例,或者獲取到的bean實(shí)例數(shù)超過(guò)1個(gè)祠够,則拋出異常压汪。
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 4.1
*/
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
/**
* 獲取bean提供者對(duì)象,用于延遲創(chuàng)建古瓤。
* Return a provider for the specified bean, allowing for lazy on-demand retrieval
* of instances, including availability and uniqueness options.
* @param requiredType type the bean must match; can be an interface or superclass
* @return a corresponding provider handle
* @since 5.1
* @see #getBeanProvider(ResolvableType)
*/
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
/**
* 根據(jù)特定類型獲取bean提供者對(duì)象蛾魄,用于延遲創(chuàng)建
* Return a provider for the specified bean, allowing for lazy on-demand retrieval
* of instances, including availability and uniqueness options.
* @param requiredType type the bean must match; can be a generic type declaration.
* Note that collection types are not supported here, in contrast to reflective
* injection points. For programmatically retrieving a list of beans matching a
* specific type, specify the actual bean type as an argument here and subsequently
* use {@link ObjectProvider#orderedStream()} or its lazy streaming/iteration options.
* @return a corresponding provider handle
* @since 5.1
* @see ObjectProvider#iterator()
* @see ObjectProvider#stream()
* @see ObjectProvider#orderedStream()
*/
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
/**
* 是否包含特定名稱的bean實(shí)例
* Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name?
* <p>If the given name is an alias, it will be translated back to the corresponding
* canonical bean name.
* <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
* be found in this factory instance.
* <p>If a bean definition or singleton instance matching the given name is found,
* this method will return {@code true} whether the named bean definition is concrete
* or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
* return value from this method does not necessarily indicate that {@link #getBean}
* will be able to obtain an instance for the same name.
* @param name the name of the bean to query
* @return whether a bean with the given name is present
*/
boolean containsBean(String name);
/**
* 特定名稱的bean類型是否為單例
* Is this bean a shared singleton? That is, will {@link #getBean} always
* return the same instance?
* <p>Note: This method returning {@code false} does not clearly indicate
* independent instances. It indicates non-singleton instances, which may correspond
* to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly
* check for independent instances.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean corresponds to a singleton instance
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @see #getBean
* @see #isPrototype
*/
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
/**
* 特定名稱的bean類型是否為原型類型
* Is this bean a prototype? That is, will {@link #getBean} always return
* independent instances?
* <p>Note: This method returning {@code false} does not clearly indicate
* a singleton object. It indicates non-independent instances, which may correspond
* to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly
* check for a shared singleton instance.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean will always deliver independent instances
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.3
* @see #getBean
* @see #isSingleton
*/
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
/**
* 特定名稱的bean的類型,是否和傳入的類型匹配湿滓,這兒的類型指的是Spring通用類型
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code ResolvableType})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 4.2
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
/**
* 特定名稱的bean的類型,是否和傳入的類型匹配舌狗,這兒的類型指的是Class
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code Class})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.1
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
/**
* 根據(jù)bean的名稱叽奥,獲取bean的類型(Class)
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}. This may lead to the initialization
* of a previously uninitialized {@code FactoryBean} (see {@link #getType(String, boolean)}).
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 1.1.2
* @see #getBean
* @see #isTypeMatch
*/
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
/**
* 根據(jù)bean的名稱,獲取bean的類型(Class)痛侍,同時(shí)根據(jù)參數(shù)判斷是否允許進(jìn)行FactoryBean的初始化
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}. Depending on the
* {@code allowFactoryBeanInit} flag, this may lead to the initialization of a previously
* uninitialized {@code FactoryBean} if no early type information is available.
* <p>Translates aliases back to the corresponding canonical bean name.
* Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param allowFactoryBeanInit whether a {@code FactoryBean} may get initialized
* just for the purpose of determining its object type
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 5.2
* @see #getBean
* @see #isTypeMatch
*/
@Nullable
Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
/**
* 獲取指定名稱bean的所有別名數(shù)組
* Return the aliases for the given bean name, if any.
* All of those aliases point to the same bean when used in a {@link #getBean} call.
* <p>If the given name is an alias, the corresponding original bean name
* and other aliases (if any) will be returned, with the original bean name
* being the first element in the array.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the bean name to check for aliases
* @return the aliases, or an empty array if none
* @see #getBean
*/
String[] getAliases(String name);
}
HierarchicalBeanFactory
public interface HierarchicalBeanFactory extends BeanFactory {
/**
* 獲取父類beanFactory
* Return the parent bean factory, or {@code null} if there is none.
*/
@Nullable
BeanFactory getParentBeanFactory();
/**
* 判斷指定名稱的bean是否包含在當(dāng)前的beanFactory中
* 【注意】:如果包含在繼承的beanFactory中朝氓,那么返回false
* Return whether the local bean factory contains a bean of the given name,
* ignoring beans defined in ancestor contexts.
* <p>This is an alternative to {@code containsBean}, ignoring a bean
* of the given name from an ancestor bean factory.
* @param name the name of the bean to query
* @return whether a bean with the given name is defined in the local factory
* @see BeanFactory#containsBean
*/
boolean containsLocalBean(String name);
}
ConfigurableBeanFactory
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
/**
* 單例bean范圍的標(biāo)識(shí)符
*/
String SCOPE_SINGLETON = "singleton";
/**
* 原型bean范圍的標(biāo)識(shí)符
*/
String SCOPE_PROTOTYPE = "prototype";
/**
* 設(shè)置父類工廠
*/
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
/**
* 設(shè)置bean的類加載器
*/
void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);
/**
* 獲取bean的類加載器
*/
@Nullable
ClassLoader getBeanClassLoader();
/**
* 設(shè)置臨時(shí)的類加載器,臨時(shí)的類加載器主届,主要在`load-time weaving`場(chǎng)景使用赵哲,以確保bean的加載盡可能地延遲。
* 當(dāng)所有bean加載完成之后君丁,該類加載器將從Beanfactory自動(dòng)移除枫夺。
*/
void setTempClassLoader(@Nullable ClassLoader tempClassLoader);
/**
* 獲取臨時(shí)的類加載器
* @since 2.5
*/
@Nullable
ClassLoader getTempClassLoader();
/**
* 設(shè)置是否緩存bean元數(shù)據(jù),例如BeanDefination绘闷。
*/
void setCacheBeanMetadata(boolean cacheBeanMetadata);
/**
* 獲取是否緩存bean元數(shù)據(jù)
*/
boolean isCacheBeanMetadata();
/**
* 設(shè)置bean表達(dá)式處理器橡庞,例如`#{...}`的操作。
* Specify the resolution strategy for expressions in bean definition values.
* <p>There is no expression support active in a BeanFactory by default.
* An ApplicationContext will typically set a standard expression strategy
* here, supporting "#{...}" expressions in a Unified EL compatible style.
* @since 3.0
*/
void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);
/**
* 獲取bean表達(dá)式處理器
* Return the resolution strategy for expressions in bean definition values.
* @since 3.0
*/
@Nullable
BeanExpressionResolver getBeanExpressionResolver();
/**
* 設(shè)置轉(zhuǎn)換服務(wù)
* @since 3.0
*/
void setConversionService(@Nullable ConversionService conversionService);
/**
* 獲取轉(zhuǎn)換服務(wù)
* @since 3.0
*/
@Nullable
ConversionService getConversionService();
/**
* 添加一個(gè)屬性編輯器注冊(cè)器印蔗,用于所有bean的創(chuàng)建過(guò)程扒最。
* 每個(gè)bean在創(chuàng)建的時(shí)候都會(huì)創(chuàng)建一個(gè)獨(dú)立的屬性編輯器實(shí)例,因此它是線程安全的
* Add a PropertyEditorRegistrar to be applied to all bean creation processes.
* <p>Such a registrar creates new PropertyEditor instances and registers them
* on the given registry, fresh for each bean creation attempt. This avoids
* the need for synchronization on custom editors; hence, it is generally
* preferable to use this method instead of {@link #registerCustomEditor}.
* @param registrar the PropertyEditorRegistrar to register
*/
void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);
/**
* 注冊(cè)一個(gè)自定義屬性編輯器
* 所有的bean都公用這個(gè)屬性編輯器华嘹,因此它會(huì)在鎖環(huán)境下使用吧趣,目的是確保線程安全。
* Register the given custom property editor for all properties of the
* given type. To be invoked during factory configuration.
* <p>Note that this method will register a shared custom editor instance;
* access to that instance will be synchronized for thread-safety. It is
* generally preferable to use {@link #addPropertyEditorRegistrar} instead
* of this method, to avoid for the need for synchronization on custom editors.
* @param requiredType type of the property
* @param propertyEditorClass the {@link PropertyEditor} class to register
*/
void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);
/**
* 拷貝屬性編輯器注冊(cè)器
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* @param registry the PropertyEditorRegistry to initialize
*/
void copyRegisteredEditorsTo(PropertyEditorRegistry registry);
/**
* 設(shè)置自定義的類型轉(zhuǎn)換器
* Set a custom type converter that this BeanFactory should use for converting
* bean property values, constructor argument values, etc.
* <p>This will override the default PropertyEditor mechanism and hence make
* any custom editors or custom editor registrars irrelevant.
* @since 2.5
* @see #addPropertyEditorRegistrar
* @see #registerCustomEditor
*/
void setTypeConverter(TypeConverter typeConverter);
/**
* 獲取自定義類型轉(zhuǎn)換器
* Obtain a type converter as used by this BeanFactory. This may be a fresh
* instance for each call, since TypeConverters are usually <i>not</i> thread-safe.
* <p>If the default PropertyEditor mechanism is active, the returned
* TypeConverter will be aware of all custom editors that have been registered.
* @since 2.5
*/
TypeConverter getTypeConverter();
/**
* 獲取內(nèi)嵌的值處理器
* Add a String resolver for embedded values such as annotation attributes.
* @param valueResolver the String resolver to apply to embedded values
* @since 3.0
*/
void addEmbeddedValueResolver(StringValueResolver valueResolver);
/**
* 判斷是否有內(nèi)嵌的值處理器
* Determine whether an embedded value resolver has been registered with this
* bean factory, to be applied through {@link #resolveEmbeddedValue(String)}.
* @since 4.3
*/
boolean hasEmbeddedValueResolver();
/**
* 使用內(nèi)嵌的值處理器對(duì)值進(jìn)行處理耙厚。
* Resolve the given embedded value, e.g. an annotation attribute.
* @param value the value to resolve
* @return the resolved value (may be the original value as-is)
* @since 3.0
*/
@Nullable
String resolveEmbeddedValue(String value);
/**
* 添加一個(gè)BeanPostProcessor實(shí)例
* Add a new BeanPostProcessor that will get applied to beans created
* by this factory. To be invoked during factory configuration.
* <p>Note: Post-processors submitted here will be applied in the order of
* registration; any ordering semantics expressed through implementing the
* {@link org.springframework.core.Ordered} interface will be ignored. Note
* that autodetected post-processors (e.g. as beans in an ApplicationContext)
* will always be applied after programmatically registered ones.
* @param beanPostProcessor the post-processor to register
*/
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
/**
* 獲取BeanPostProcessor實(shí)例數(shù)
* Return the current number of registered BeanPostProcessors, if any.
*/
int getBeanPostProcessorCount();
/**
* 注冊(cè)特定類型的scope强挫,比如Request或者Session
* Register the given scope, backed by the given Scope implementation.
* @param scopeName the scope identifier
* @param scope the backing Scope implementation
*/
void registerScope(String scopeName, Scope scope);
/**
* 獲取已注冊(cè)scope名稱數(shù)組
* Return the names of all currently registered scopes.
* <p>This will only return the names of explicitly registered scopes.
* Built-in scopes such as "singleton" and "prototype" won't be exposed.
* @return the array of scope names, or an empty array if none
* @see #registerScope
*/
String[] getRegisteredScopeNames();
/**
* 獲取特定名稱的scope
* Return the Scope implementation for the given scope name, if any.
* <p>This will only return explicitly registered scopes.
* Built-in scopes such as "singleton" and "prototype" won't be exposed.
* @param scopeName the name of the scope
* @return the registered Scope implementation, or {@code null} if none
* @see #registerScope
*/
@Nullable
Scope getRegisteredScope(String scopeName);
/**
* 獲取訪問(wèn)控制上下文
* Provides a security access control context relevant to this factory.
* @return the applicable AccessControlContext (never {@code null})
* @since 3.0
*/
AccessControlContext getAccessControlContext();
/**
* 從特定的可配置BeanFactory實(shí)例中拷貝配置。注意颜曾,這兒說(shuō)的是“配置”
* 包括:BeanPostProcessors, Scopes, and factory-specific internal settings.
* 不包括: any metadata of actual bean definitions,
*
* Copy all relevant configuration from the given other factory.
* <p>Should include all standard configuration settings as well as
* BeanPostProcessors, Scopes, and factory-specific internal settings.
* Should not include any metadata of actual bean definitions,
* such as BeanDefinition objects and bean name aliases.
* @param otherFactory the other BeanFactory to copy from
*/
void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);
/**
* 給bean注冊(cè)別名
* Given a bean name, create an alias. We typically use this method to
* support names that are illegal within XML ids (used for bean names).
* <p>Typically invoked during factory configuration, but can also be
* used for runtime registration of aliases. Therefore, a factory
* implementation should synchronize alias access.
* @param beanName the canonical name of the target bean
* @param alias the alias to be registered for the bean
* @throws BeanDefinitionStoreException if the alias is already in use
*/
void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException;
/**
* 使用特定的值處理器纠拔,處理所有別名
* Resolve all alias target names and aliases registered in this
* factory, applying the given 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
* @since 2.5
*/
void resolveAliases(StringValueResolver valueResolver);
/**
* 獲取一個(gè)合并的BeanDefinition,子類的話泛豪,可以將父類的屬性也合并過(guò)來(lái)
* Return a merged BeanDefinition for the given bean name,
* merging a child bean definition with its parent if necessary.
* Considers bean definitions in ancestor factories as well.
* @param beanName the name of the bean to retrieve the merged definition for
* @return a (potentially merged) BeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean definition with the given name
* @since 2.5
*/
BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
/**
* 是否工廠bean
* Determine whether the bean with the given name is a FactoryBean.
* @param name the name of the bean to check
* @return whether the bean is a FactoryBean
* ({@code false} means the bean exists but is not a FactoryBean)
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.5
*/
boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;
/**
* 設(shè)置特定名稱的bean是否在創(chuàng)建過(guò)程中
* Explicitly control the current in-creation status of the specified bean.
* For container-internal use only.
* @param beanName the name of the bean
* @param inCreation whether the bean is currently in creation
* @since 3.1
*/
void setCurrentlyInCreation(String beanName, boolean inCreation);
/**
* 判斷特定名稱的bean是否在創(chuàng)建過(guò)程中
* Determine whether the specified bean is currently in creation.
* @param beanName the name of the bean
* @return whether the bean is currently in creation
* @since 2.5
*/
boolean isCurrentlyInCreation(String beanName);
/**
* 注冊(cè)bean之間的依賴關(guān)系
* Register a dependent bean for the given bean,
* to be destroyed before the given bean is destroyed.
* @param beanName the name of the bean
* @param dependentBeanName the name of the dependent bean
* @since 2.5
*/
void registerDependentBean(String beanName, String dependentBeanName);
/**
* 獲取所有依賴特定名稱bean的bean名稱
* Return the names of all beans which depend on the specified bean, if any.
* @param beanName the name of the bean
* @return the array of dependent bean names, or an empty array if none
* @since 2.5
*/
String[] getDependentBeans(String beanName);
/**
* 獲取特定名稱bean的所有依賴bean
* Return the names of all beans that the specified bean depends on, if any.
* @param beanName the name of the bean
* @return the array of names of beans which the bean depends on,
* or an empty array if none
* @since 2.5
*/
String[] getDependenciesForBean(String beanName);
/**
* 銷毀bean
* Destroy the given bean instance (usually a prototype instance
* obtained from this factory) according to its bean definition.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param beanName the name of the bean definition
* @param beanInstance the bean instance to destroy
*/
void destroyBean(String beanName, Object beanInstance);
/**
* 在特定scope下稠诲,銷毀指定名稱的bean對(duì)象
* Destroy the specified scoped bean in the current target scope, if any.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param beanName the name of the scoped bean
*/
void destroyScopedBean(String beanName);
/**
* 銷毀單例
* Destroy all singleton beans in this factory, including inner beans that have
* been registered as disposable. To be called on shutdown of a factory.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
*/
void destroySingletons();
}
AutowireCapableBeanFactory
public interface AutowireCapableBeanFactory extends BeanFactory {
/**
* 沒(méi)有外部依賴的注入方式
* Constant that indicates no externally defined autowiring. Note that
* BeanFactoryAware etc and annotation-driven injection will still be applied.
* @see #createBean
* @see #autowire
* @see #autowireBeanProperties
*/
int AUTOWIRE_NO = 0;
/**
* 按照名稱注入
* Constant that indicates autowiring bean properties by name
* (applying to all bean property setters).
* @see #createBean
* @see #autowire
* @see #autowireBeanProperties
*/
int AUTOWIRE_BY_NAME = 1;
/**
* 按照類型注入
* Constant that indicates autowiring bean properties by type
* (applying to all bean property setters).
* @see #createBean
* @see #autowire
* @see #autowireBeanProperties
*/
int AUTOWIRE_BY_TYPE = 2;
/**
* 以構(gòu)造器的方式注入
* Constant that indicates autowiring the greediest constructor that
* can be satisfied (involves resolving the appropriate constructor).
* @see #createBean
* @see #autowire
*/
int AUTOWIRE_CONSTRUCTOR = 3;
/**
* 自動(dòng)檢測(cè)的方式注入侦鹏,目前已廢棄。
* Constant that indicates determining an appropriate autowire strategy
* through introspection of the bean class.
* @see #createBean
* @see #autowire
* @deprecated as of Spring 3.0: If you are using mixed autowiring strategies,
* prefer annotation-based autowiring for clearer demarcation of autowiring needs.
*/
@Deprecated
int AUTOWIRE_AUTODETECT = 4;
/**
* Suffix for the "original instance" convention when initializing an existing
* bean instance: to be appended to the fully-qualified bean class name,
* e.g. "com.mypackage.MyClass.ORIGINAL", in order to enforce the given instance
* to be returned, i.e. no proxies etc.
* @since 5.1
* @see #initializeBean(Object, String)
* @see #applyBeanPostProcessorsBeforeInitialization(Object, String)
* @see #applyBeanPostProcessorsAfterInitialization(Object, String)
*/
String ORIGINAL_INSTANCE_SUFFIX = ".ORIGINAL";
//-------------------------------------------------------------------------
// Typical methods for creating and populating external bean instances
//-------------------------------------------------------------------------
/**
* 創(chuàng)建特定類型的bean實(shí)例臀叙,將會(huì)執(zhí)行完整的bean初始化略水,包括BeanPostProcessors操作。
* Fully create a new bean instance of the given class.
* <p>Performs full initialization of the bean, including all applicable
* {@link BeanPostProcessor BeanPostProcessors}.
* <p>Note: This is intended for creating a fresh instance, populating annotated
* fields and methods as well as applying all standard bean initialization callbacks.
* It does <i>not</i> imply traditional by-name or by-type autowiring of properties;
* use {@link #createBean(Class, int, boolean)} for those purposes.
* @param beanClass the class of the bean to create
* @return the new bean instance
* @throws BeansException if instantiation or wiring failed
*/
<T> T createBean(Class<T> beanClass) throws BeansException;
/**
* 注入bean
* Populate the given bean instance through applying after-instantiation callbacks
* and bean property post-processing (e.g. for annotation-driven injection).
* <p>Note: This is essentially intended for (re-)populating annotated fields and
* methods, either for new instances or for deserialized instances. It does
* <i>not</i> imply traditional by-name or by-type autowiring of properties;
* use {@link #autowireBeanProperties} for those purposes.
* @param existingBean the existing bean instance
* @throws BeansException if wiring failed
*/
void autowireBean(Object existingBean) throws BeansException;
/**
* 配置bean劝萤,包括注入屬性渊涝,解決bean屬性值,應(yīng)用bean工廠回調(diào)床嫌,應(yīng)用beanPostProcessor
* Configure the given raw bean: autowiring bean properties, applying
* bean property values, applying factory callbacks such as {@code setBeanName}
* and {@code setBeanFactory}, and also applying all bean post processors
* (including ones which might wrap the given raw bean).
* <p>This is effectively a superset of what {@link #initializeBean} provides,
* fully applying the configuration specified by the corresponding bean definition.
* <b>Note: This method requires a bean definition for the given name!</b>
* @param existingBean the existing bean instance
* @param beanName the name of the bean, to be passed to it if necessary
* (a bean definition of that name has to be available)
* @return the bean instance to use, either the original or a wrapped one
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* if there is no bean definition with the given name
* @throws BeansException if the initialization failed
* @see #initializeBean
*/
Object configureBean(Object existingBean, String beanName) throws BeansException;
//-------------------------------------------------------------------------
// Specialized methods for fine-grained control over the bean lifecycle
//-------------------------------------------------------------------------
/**
* 創(chuàng)建bean
* Fully create a new bean instance of the given class with the specified
* autowire strategy. All constants defined in this interface are supported here.
* <p>Performs full initialization of the bean, including all applicable
* {@link BeanPostProcessor BeanPostProcessors}. This is effectively a superset
* of what {@link #autowire} provides, adding {@link #initializeBean} behavior.
* @param beanClass the class of the bean to create
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for objects
* (not applicable to autowiring a constructor, thus ignored there)
* @return the new bean instance
* @throws BeansException if instantiation or wiring failed
* @see #AUTOWIRE_NO
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_CONSTRUCTOR
*/
Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
/**
* 使用特定的注入策略跨释,實(shí)例化并注入一個(gè)bean
* Instantiate a new bean instance of the given class with the specified autowire
* strategy. All constants defined in this interface are supported here.
* Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
* before-instantiation callbacks (e.g. for annotation-driven injection).
* <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
* callbacks or perform any further initialization of the bean. This interface
* offers distinct, fine-grained operations for those purposes, for example
* {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
* callbacks are applied, if applicable to the construction of the instance.
* @param beanClass the class of the bean to instantiate
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for object
* references in the bean instance (not applicable to autowiring a constructor,
* thus ignored there)
* @return the new bean instance
* @throws BeansException if instantiation or wiring failed
* @see #AUTOWIRE_NO
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_CONSTRUCTOR
* @see #AUTOWIRE_AUTODETECT
* @see #initializeBean
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #applyBeanPostProcessorsAfterInitialization
*/
Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
/**
* 使用特定的注入策略,注入指定bean的所有屬性
* Autowire the bean properties of the given bean instance by name or type.
* Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
* after-instantiation callbacks (e.g. for annotation-driven injection).
* <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
* callbacks or perform any further initialization of the bean. This interface
* offers distinct, fine-grained operations for those purposes, for example
* {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
* callbacks are applied, if applicable to the configuration of the instance.
* @param existingBean the existing bean instance
* @param autowireMode by name or type, using the constants in this interface
* @param dependencyCheck whether to perform a dependency check for object
* references in the bean instance
* @throws BeansException if wiring failed
* @see #AUTOWIRE_BY_NAME
* @see #AUTOWIRE_BY_TYPE
* @see #AUTOWIRE_NO
*/
void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
throws BeansException;
/**
* 解決bean屬性的值厌处,該方法不會(huì)注入bean的屬性鳖谈,而只是應(yīng)用已經(jīng)存在的屬性。
* 我們可以使用`autowireBeanProperties`來(lái)注入屬性
* Apply the property values of the bean definition with the given name to
* the given bean instance. The bean definition can either define a fully
* self-contained bean, reusing its property values, or just property values
* meant to be used for existing bean instances.
* <p>This method does <i>not</i> autowire bean properties; it just applies
* explicitly defined property values. Use the {@link #autowireBeanProperties}
* method to autowire an existing bean instance.
* <b>Note: This method requires a bean definition for the given name!</b>
* <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
* callbacks or perform any further initialization of the bean. This interface
* offers distinct, fine-grained operations for those purposes, for example
* {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
* callbacks are applied, if applicable to the configuration of the instance.
* @param existingBean the existing bean instance
* @param beanName the name of the bean definition in the bean factory
* (a bean definition of that name has to be available)
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* if there is no bean definition with the given name
* @throws BeansException if applying the property values failed
* @see #autowireBeanProperties
*/
void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;
/**
* 初始化bean
* Initialize the given raw bean, applying factory callbacks
* such as {@code setBeanName} and {@code setBeanFactory},
* also applying all bean post processors (including ones which
* might wrap the given raw bean).
* <p>Note that no bean definition of the given name has to exist
* in the bean factory. The passed-in bean name will simply be used
* for callbacks but not checked against the registered bean definitions.
* @param existingBean the existing bean instance
* @param beanName the name of the bean, to be passed to it if necessary
* (only passed to {@link BeanPostProcessor BeanPostProcessors};
* can follow the {@link #ORIGINAL_INSTANCE_SUFFIX} convention in order to
* enforce the given instance to be returned, i.e. no proxies etc)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if the initialization failed
* @see #ORIGINAL_INSTANCE_SUFFIX
*/
Object initializeBean(Object existingBean, String beanName) throws BeansException;
/**
* 應(yīng)用`BeanPostProcessor`進(jìn)行bean實(shí)例化后阔涉,初始化前的處理
* Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean
* instance, invoking their {@code postProcessBeforeInitialization} methods.
* The returned bean instance may be a wrapper around the original.
* @param existingBean the existing bean instance
* @param beanName the name of the bean, to be passed to it if necessary
* (only passed to {@link BeanPostProcessor BeanPostProcessors};
* can follow the {@link #ORIGINAL_INSTANCE_SUFFIX} convention in order to
* enforce the given instance to be returned, i.e. no proxies etc)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessBeforeInitialization
* @see #ORIGINAL_INSTANCE_SUFFIX
*/
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException;
/**
* 應(yīng)用`BeanPostProcessor`進(jìn)行bean初始化后的處理
* Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean
* instance, invoking their {@code postProcessAfterInitialization} methods.
* The returned bean instance may be a wrapper around the original.
* @param existingBean the existing bean instance
* @param beanName the name of the bean, to be passed to it if necessary
* (only passed to {@link BeanPostProcessor BeanPostProcessors};
* can follow the {@link #ORIGINAL_INSTANCE_SUFFIX} convention in order to
* enforce the given instance to be returned, i.e. no proxies etc)
* @return the bean instance to use, either the original or a wrapped one
* @throws BeansException if any post-processing failed
* @see BeanPostProcessor#postProcessAfterInitialization
* @see #ORIGINAL_INSTANCE_SUFFIX
*/
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException;
/**
* 銷毀一個(gè)已存在的bean
* Destroy the given bean instance (typically coming from {@link #createBean}),
* applying the {@link org.springframework.beans.factory.DisposableBean} contract as well as
* registered {@link DestructionAwareBeanPostProcessor DestructionAwareBeanPostProcessors}.
* <p>Any exception that arises during destruction should be caught
* and logged instead of propagated to the caller of this method.
* @param existingBean the bean instance to destroy
*/
void destroyBean(Object existingBean);
//-------------------------------------------------------------------------
// Delegate methods for resolving injection points
//-------------------------------------------------------------------------
/**
* 根據(jù)類型缆娃,獲取bean名稱持有者對(duì)象,bean不存在或超過(guò)一個(gè)瑰排,都將拋出異常贯要。
* Resolve the bean instance that uniquely matches the given object type, if any,
* including its bean name.
* <p>This is effectively a variant of {@link #getBean(Class)} which preserves the
* bean name of the matching instance.
* @param requiredType type the bean must match; can be an interface or superclass
* @return the bean name plus bean instance
* @throws NoSuchBeanDefinitionException if no matching bean was found
* @throws NoUniqueBeanDefinitionException if more than one matching bean was found
* @throws BeansException if the bean could not be created
* @since 4.3.3
* @see #getBean(Class)
*/
<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;
/**
* 根據(jù)名稱,獲取bean名稱持有者對(duì)象椭住,bean不存在崇渗,將拋出異常。
* Resolve a bean instance for the given bean name, providing a dependency descriptor
* for exposure to target factory methods.
* <p>This is effectively a variant of {@link #getBean(String, Class)} which supports
* factory methods with an {@link org.springframework.beans.factory.InjectionPoint}
* argument.
* @param name the name of the bean to look up
* @param descriptor the dependency descriptor for the requesting injection point
* @return the corresponding bean instance
* @throws NoSuchBeanDefinitionException if there is no bean with the specified name
* @throws BeansException if the bean could not be created
* @since 5.1.5
* @see #getBean(String, Class)
*/
Object resolveBeanByName(String name, DependencyDescriptor descriptor) throws BeansException;
/**
* Resolve the specified dependency against the beans defined in this factory.
* @param descriptor the descriptor for the dependency (field/method/constructor)
* @param requestingBeanName the name of the bean which declares the given dependency
* @return the resolved object, or {@code null} if none found
* @throws NoSuchBeanDefinitionException if no matching bean was found
* @throws NoUniqueBeanDefinitionException if more than one matching bean was found
* @throws BeansException if dependency resolution failed for any other reason
* @since 2.5
* @see #resolveDependency(DependencyDescriptor, String, Set, TypeConverter)
*/
@Nullable
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;
/**
* Resolve the specified dependency against the beans defined in this factory.
* @param descriptor the descriptor for the dependency (field/method/constructor)
* @param requestingBeanName the name of the bean which declares the given dependency
* @param autowiredBeanNames a Set that all names of autowired beans (used for
* resolving the given dependency) are supposed to be added to
* @param typeConverter the TypeConverter to use for populating arrays and collections
* @return the resolved object, or {@code null} if none found
* @throws NoSuchBeanDefinitionException if no matching bean was found
* @throws NoUniqueBeanDefinitionException if more than one matching bean was found
* @throws BeansException if dependency resolution failed for any other reason
* @since 2.5
* @see DependencyDescriptor
*/
@Nullable
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;
}
這個(gè)工廠的應(yīng)用場(chǎng)景函荣,可參考文章:http://www.reibang.com/p/d564335fafab
ListableBeanFactory
public interface ListableBeanFactory extends BeanFactory {
/**
* 是否包含bean的定義
*/
boolean containsBeanDefinition(String beanName);
/**
* 獲取bean的定義數(shù)
*/
int getBeanDefinitionCount();
/**
* 獲取bean定義名稱數(shù)組
*/
String[] getBeanDefinitionNames();
/**
* 獲取特定類型的bean名稱數(shù)組
*/
String[] getBeanNamesForType(ResolvableType type);
/**
* 獲取特定類型的bean名稱數(shù)組显押,同時(shí)去掉非單例類型,且允許提前初始化
*/
String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit);
/**
* 獲取特定類型的bean名稱數(shù)組
*/
String[] getBeanNamesForType(@Nullable Class<?> type);
/**
* 獲取特定類型的bean名稱數(shù)組傻挂,同時(shí)去掉非單例類型乘碑,且允許提前初始化
*/
String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
/**
* 獲取特定類型的bean map,key為bean的名稱金拒,value為bean對(duì)象
*/
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;
/**
* 獲取特定類型的bean map兽肤,key為bean的名稱,value為bean對(duì)象
* 同時(shí)去掉非單例類型绪抛,且允許提前初始化
*/
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException;
/**
* 獲取有特定注解修飾的bean名稱數(shù)組
*/
String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);
/**
* 獲取有特定注解修飾的bean map资铡,key為bean的名稱,value為bean對(duì)象
*/
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;
/**
* 獲取特定名稱的bean的特定類型注解
*/
@Nullable
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException;
}
ConfigurableListableBeanFactory
public interface ConfigurableListableBeanFactory
extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
/**
* 在注入的時(shí)候幢码,忽略特定類型的依賴
*/
void ignoreDependencyType(Class<?> type);
/**
* 忽略特定接口的依賴注入笤休,
* 比如BeanFactory會(huì)忽略BeanFactoryAware的注入
* 再比如ApplicationContext會(huì)忽略ApplicationContextAware的注入
* Ignore the given dependency interface for autowiring.
* <p>This will typically be used by application contexts to register
* dependencies that are resolved in other ways, like BeanFactory through
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.
* <p>By default, only the BeanFactoryAware interface is ignored.
* For further types to ignore, invoke this method for each type.
* @param ifc the dependency interface to ignore
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.context.ApplicationContextAware
*/
void ignoreDependencyInterface(Class<?> ifc);
/**
* 針對(duì)特定類型,注入特定的值症副,
* 比如一個(gè)單例bean依賴ApplicationContext店雅,而ApplicationContext并非一個(gè)bean對(duì)象
* Register a special dependency type with corresponding autowired value.
* <p>This is intended for factory/context references that are supposed
* to be autowirable but are not defined as beans in the factory:
* e.g. a dependency of type ApplicationContext resolved to the
* ApplicationContext instance that the bean is living in.
* <p>Note: There are no such default types registered in a plain BeanFactory,
* not even for the BeanFactory interface itself.
* @param dependencyType the dependency type to register. This will typically
* be a base interface such as BeanFactory, with extensions of it resolved
* as well if declared as an autowiring dependency (e.g. ListableBeanFactory),
* as long as the given value actually implements the extended interface.
* @param autowiredValue the corresponding autowired value. This may also be an
* implementation of the {@link org.springframework.beans.factory.ObjectFactory}
* interface, which allows for lazy resolution of the actual target value.
*/
void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue);
/**
* bean是否作為一個(gè)注入的候選者
* Determine whether the specified bean qualifies as an autowire candidate,
* to be injected into other beans which declare a dependency of matching type.
* <p>This method checks ancestor factories as well.
* @param beanName the name of the bean to check
* @param descriptor the descriptor of the dependency to resolve
* @return whether the bean should be considered as autowire candidate
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
*/
boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
throws NoSuchBeanDefinitionException;
/**
* 獲取bean定義
* Return the registered BeanDefinition for the specified bean, allowing access
* to its property values and constructor argument value (which can be
* modified during bean factory post-processing).
* <p>A returned BeanDefinition object should not be a copy but the original
* definition object as registered in the factory. This means that it should
* be castable to a more specific implementation type, if necessary.
* <p><b>NOTE:</b> This method does <i>not</i> consider ancestor factories.
* It is only meant for accessing local bean definitions of this factory.
* @param beanName the name of the bean
* @return the registered BeanDefinition
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* defined in this factory
*/
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
/**
* 獲取bean名稱迭代器
* Return a unified view over all bean names managed by this factory.
* <p>Includes bean definition names as well as names of manually registered
* singleton instances, with bean definition names consistently coming first,
* analogous to how type/annotation specific retrieval of bean names works.
* @return the composite iterator for the bean names view
* @since 4.1.2
* @see #containsBeanDefinition
* @see #registerSingleton
* @see #getBeanNamesForType
* @see #getBeanNamesForAnnotation
*/
Iterator<String> getBeanNamesIterator();
/**
* 清除元數(shù)據(jù)緩存
* Clear the merged bean definition cache, removing entries for beans
* which are not considered eligible for full metadata caching yet.
* <p>Typically triggered after changes to the original bean definitions,
* e.g. after applying a {@link BeanFactoryPostProcessor}. Note that metadata
* for beans which have already been created at this point will be kept around.
* @since 4.2
* @see #getBeanDefinition
* @see #getMergedBeanDefinition
*/
void clearMetadataCache();
/**
* 凍結(jié)bean配置政基,從而導(dǎo)致bean定義不能被修改,也不能進(jìn)一步操作
* Freeze all bean definitions, signalling that the registered bean definitions
* will not be modified or post-processed any further.
* <p>This allows the factory to aggressively cache bean definition metadata.
*/
void freezeConfiguration();
/**
* bean配置是否被凍結(jié)
* Return whether this factory's bean definitions are frozen,
* i.e. are not supposed to be modified or post-processed any further.
* @return {@code true} if the factory's configuration is considered frozen
*/
boolean isConfigurationFrozen();
/**
* 預(yù)初始化單例bean對(duì)象
* Ensure that all non-lazy-init singletons are instantiated, also considering
* {@link org.springframework.beans.factory.FactoryBean FactoryBeans}.
* Typically invoked at the end of factory setup, if desired.
* @throws BeansException if one of the singleton beans could not be created.
* Note: This may have left the factory with some beans already initialized!
* Call {@link #destroySingletons()} for full cleanup in this case.
* @see #destroySingletons()
*/
void preInstantiateSingletons() throws BeansException;
}
總結(jié)
本文分析了Spring自帶的闹啦、我們經(jīng)常使用到的BeanFactory相關(guān)接口沮明,功能繁多,但結(jié)構(gòu)清晰窍奋。
我們對(duì)此進(jìn)行了詳細(xì)分析荐健,已經(jīng)基本知道其包含的內(nèi)容,以及要實(shí)現(xiàn)的功能了琳袄。