Spring源碼學習之BeanFactory體繫結構

来源:http://www.cnblogs.com/ToBeAProgrammer/archive/2016/02/16/5192837.html
-Advertisement-
Play Games

一.BeanFactory BeanFactory是Spring IOC容器的鼻祖,是IOC容器的基礎介面,所有的容器都是從它這裡繼承實現而來。可見其地位。BeanFactory提供了最基本的IOC容器的功能,即所有的容器至少需要實現的標準。 BeanFactory體繫結構是典型的工廠方法模式,即什


一.BeanFactory

BeanFactory是Spring IOC容器的鼻祖,是IOC容器的基礎介面,所有的容器都是從它這裡繼承實現而來。可見其地位。BeanFactory提供了最基本的IOC容器的功能,即所有的容器至少需要實現的標準。

 

      BeanFactory體繫結構是典型的工廠方法模式,即什麼樣的工廠生產什麼樣的產品。BeanFactory是最基本的抽象工廠,而其他的IOC容器只不過是具體的工廠,對應著各自的Bean定義方法。但同時,其他容器也針對具體場景不同,進行了擴充,提供具體的服務。

二.BeanFacory源碼

1.java doc

首先是Java doc,現在閱讀源碼的習慣是一定要理解了java doc的描述,因為這裡是作者的描述,沒有人比作者更明白這個類,這個介面要乾什麼。

/**
 * The root interface for accessing a Spring bean container.
 * This is the basic client view of a bean container;
 * further interfaces such as {@link ListableBeanFactory} and
 * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
 * are available for specific purposes.
 *
 * <p>This interface is implemented by objects that hold a number of bean definitions,
 * each uniquely identified by a String name. Depending on the bean definition,
 * the factory will return either an independent instance of a contained object
 * (the Prototype design pattern), or a single shared instance (a superior
 * alternative to the Singleton design pattern, in which the instance is a
 * singleton in the scope of the factory). Which type of instance will be returned
 * depends on the bean factory configuration: the API is the same. Since Spring
 * 2.0, further scopes are available depending on the concrete application
 * context (e.g. "request" and "session" scopes in a web environment).
 *
 * <p>The point of this approach is that the BeanFactory is a central registry
 * of application components, and centralizes configuration of application
 * components (no more do individual objects need to read properties files,
 * for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and
 * Development" for a discussion of the benefits of this approach.
 *
 * <p>Note that it is generally better to rely on Dependency Injection
 * ("push" configuration) to configure application objects through setters
 * or constructors, rather than use any form of "pull" configuration like a
 * BeanFactory lookup. Spring's Dependency Injection functionality is
 * implemented using this BeanFactory interface and its subinterfaces.
 *
 * <p>Normally a BeanFactory will load bean definitions stored in a configuration
 * source (such as an XML document), and use the {@code org.springframework.beans}
 * package to configure the beans. However, an implementation could simply return
 * Java objects it creates as necessary directly in Java code. There are no
 * constraints on how the definitions could be stored: LDAP, RDBMS, XML,
 * properties file, etc. Implementations are encouraged to support references
 * amongst beans (Dependency Injection).
 *
 * <p>In contrast to the methods in {@link ListableBeanFactory}, all of the
 * operations in this interface will also check parent factories if this is a
 * {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance,
 * the immediate parent factory will be asked. Beans in this factory instance
 * are supposed to override beans of the same name in any parent factory.
 *
 * <p>Bean factory implementations should support the standard bean lifecycle interfaces
 * as far as possible. The full set of initialization methods and their standard order is:<br>
 * 1. BeanNameAware's {@code setBeanName}<br>
 * 2. BeanClassLoaderAware's {@code setBeanClassLoader}<br>
 * 3. BeanFactoryAware's {@code setBeanFactory}<br>
 * 4. ResourceLoaderAware's {@code setResourceLoader}
 * (only applicable when running in an application context)<br>
 * 5. ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
 * (only applicable when running in an application context)<br>
 * 6. MessageSourceAware's {@code setMessageSource}
 * (only applicable when running in an application context)<br>
 * 7. ApplicationContextAware's {@code setApplicationContext}
 * (only applicable when running in an application context)<br>
 * 8. ServletContextAware's {@code setServletContext}
 * (only applicable when running in a web application context)<br>
 * 9. {@code postProcessBeforeInitialization} methods of BeanPostProcessors<br>
 * 10. InitializingBean's {@code afterPropertiesSet}<br>
 * 11. a custom init-method definition<br>
 * 12. {@code postProcessAfterInitialization} methods of BeanPostProcessors
 *
 * <p>On shutdown of a bean factory, the following lifecycle methods apply:<br>
 * 1. DisposableBean's {@code destroy}<br>
 * 2. a custom destroy-method definition
 *

概括起來:

1.BeanFactory是Spring容器的Root Interface

2.BeanFactory的作用是持有一定數量的Bean Definition,每一個都有一個獨有的String名字。BeanFactory可以返回單例或多例的對象,取決於Bean定義文件。

3. 通過setters,constructors進行依賴註入更好,其實這也是常用的方法

4. BeanFactory通過載入配置源文件(XML文件)的方式,來配置Bean。

5. 最後一大段是BeanFactory支持的bean生命周期的順序。但是其實BeanFactory是沒有給出抽象方法的。

2.源碼

public interface BeanFactory {

    /**
     * Used to dereference a {@link FactoryBean} instance and distinguish it from
     * beans <i>created</i> by the FactoryBean. For example, if the bean named
     * {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
     * will return the factory, not the instance returned by the factory.
     */
    //使用轉義符&來得到FactoryBean本身,用來區分通過容器獲得FactoryBean本身和其產生               //的對象
    String FACTORY_BEAN_PREFIX = "&";


     //這個方法是BeanFactory的主要方法,通過這個方法,可以取得IOC容器管理的Bean,
    //Bean的取得是通過指定名字索引獲取的
    Object getBean(String name) throws BeansException;
    
    //根據bean的名字和Class類型來得到bean實例,增加了類型安全驗證機制
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;

    //通過Bean類型獲取bean實例
    <T> T getBean(Class<T> requiredType) throws BeansException;

    //增加更多獲取的條件,同上方法
    Object getBean(String name, Object... args) throws BeansException;

    
    <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;

    //判斷容器是否含有指定名字的bean
    boolean containsBean(String name);

    //查詢指定名字的Bean是不是單例的Bean
    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

    //判斷Bean是不是prototype類型的bean
    boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

    //查詢指定了名字的Bean的Class類型是否與指定類型匹配
    boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException;
    //獲取指定名字bean的Class類型
    Class<?> getType(String name) throws NoSuchBeanDefinitionException;

    //查詢指定了名字的bean的所有別名,這些別名都是在BeanDefinition中定義的
    String[] getAliases(String name);

}

這些介面定義勾畫出了IOC容器的基本方法特性。

三. BeanFactory 結構體系

BeanFactory繼承體系

BeanFactory作為最頂層的一個介面類,它定義了IOC容器的基本功能規範,BeanFactory 有三個子類介面:ListableBeanFactory、HierarchicalBeanFactory 和AutowireCapableBeanFactory,還有一個實現類SimpleJndiBeanFactory

所以接下來依次分析三個最有用的子介面。

1.AutowireCapableBeanFactory 可自動裝配的Bean工廠

值得註意的是,這個介面並沒有被ApplicationContext繼承!!這個是《Spring 技術內幕》書里寫錯的。這個介面主要是管理ApplicationContext之外的Bean。

(1)java doc

/**
 * Extension of the {@link org.springframework.beans.factory.BeanFactory}
 * interface to be implemented by bean factories that are capable of
 * autowiring, provided that they want to expose this functionality for
 * existing bean instances.
 *
 * <p>This subinterface of BeanFactory is not meant to be used in normal
 * application code: stick to {@link org.springframework.beans.factory.BeanFactory}
 * or {@link org.springframework.beans.factory.ListableBeanFactory} for
 * typical use cases.
 
     Note that this interface is not implemented by
 * {@link org.springframework.context.ApplicationContext} facades,
 * as it is hardly ever used by application code。
*/

這個工廠介面繼承自BeanFacotory,它擴展了自動裝配的功能,根據類定義BeanDefinition裝配Bean、執行前、後處理器等。主要用它來管理ApplicationContext所不能管理的那些Bean,比如Filter,Servlet等。主要通過ApplicationContext的getAutowireCapableBeanFactory()獲得實例。

(2)源碼

public interface AutowireCapableBeanFactory extends BeanFactory {

    /**
     * Constant that indicates no externally defined autowiring. Note that
     * BeanFactoryAware etc and annotation-driven injection will still be applied.
     */
    int AUTOWIRE_NO = 0;

    /**
     * Constant that indicates autowiring bean properties by name
     * (applying to all bean property setters).
     */
    int AUTOWIRE_BY_NAME = 1;

    /**
     * Constant that indicates autowiring bean properties by type
     * (applying to all bean property setters).
     */
    int AUTOWIRE_BY_TYPE = 2;

    /**
     * Constant that indicates autowiring the greediest constructor that
     * can be satisfied (involves resolving the appropriate constructor).
     */
    int AUTOWIRE_CONSTRUCTOR = 3;

    /**
     * Constant that indicates determining an appropriate autowire strategy
     * through introspection of the bean class.
     */
    @Deprecated
    int AUTOWIRE_AUTODETECT = 4;


    //-------------------------------------------------------------------------
    // Typical methods for creating and populating external bean instances
    //-------------------------------------------------------------------------

    /**
     * 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 initialiation callbacks.
     * It does <i>not</> imply traditional by-name or by-type autowiring of properties;
     * use {@link #createBean(Class, int, boolean)} for that purposes.
     */
    //通過指定的class創建一個全新的Bean實例
    <T> T createBean(Class<T> beanClass) throws BeansException;

    /**
     * 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 that purposes.
     */
    //給定對象,根據註釋,後處理器進行自動裝配
    void autowireBean(Object existingBean) throws BeansException;

    /**
     * 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>
     */
    //自動裝配Bean的屬性,應用處理器等
    Object configureBean(Object existingBean, String beanName) throws BeansException;

    /**
     * Resolve the specified dependency against the beans defined in this factory.
     */
    Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException;


    //-------------------------------------------------------------------------
    // Specialized methods for fine-grained control over the bean lifecycle
    //-------------------------------------------------------------------------

    /**
     * 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.
     * @see #AUTOWIRE_NO
     * @see #AUTOWIRE_BY_NAME
     * @see #AUTOWIRE_BY_TYPE
     * @see #AUTOWIRE_CONSTRUCTOR
     */根據給定的類型,指定的裝配策略,創建新的Bean實例
    Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

    /**
     * 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
     */
    //根據給定的策略,類型,裝配Bean屬性
    Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

    /**
     * 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;

    /**
     * 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;

    /**
     * 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})
     * @return the bean instance to use, either the original or a wrapped one
     * @throws BeansException if the initialization failed
     */
    Object initializeBean(Object existingBean, String beanName) throws BeansException;

    /**
     * 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 new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one
     * @throws BeansException if any post-processing failed
     * @see BeanPostProcessor#postProcessBeforeInitialization
     */
    Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException;

    /**
     * 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 new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one
     * @throws BeansException if any post-processing failed
     * @see BeanPostProcessor#postProcessAfterInitialization
     */
    Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException;

    /**
     * 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);

    /**
     * Resolve the specified dependency against the beans defined in this factory.
     * @param descriptor the descriptor for the dependency
     * @param beanName the name of the bean which declares the present dependency
     * @param autowiredBeanNames a Set that all names of autowired beans (used for
     * resolving the present 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 BeansException in dependency resolution failed
     */
    Object resolveDependency(DependencyDescriptor descriptor, String beanName,
            Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;

}

1.首先幾個屬性,是裝配策略

    AUTOWIRE_BY_NAME ,把與Bean的屬性具有相同的名字的其他Bean自動裝配到這個屬性上。舉個慄子就是:當有一個屬性名字為person時,則自動裝配策略選擇id為person的Bean進行裝配。

     AUTOWIRE_BY_TYPE,把與Bean的屬性具有相同的類型的其他Bean自動裝配到這個屬性。

    AUTOWIRE_BY_CONSTRUCT,把與bean的構造器入參具有相同類型的其他Bean自動裝配到Bean構造器的對應參數中。

2.重點關註兩類方法

Typical methods for creating and populating external bean instances,該類是用來根據典型方法預設創建Bean和裝配Bean的方法。

Specialized methods for fine-grained control over the bean lifecycle,該類是用來根據裝配策略細化裝配,具體控制Bean生命周期的方法。

(3)繼承體系

AutowireCapableBeanFactory繼承體系

要註意看這個實現類DefaultListableBeanFactory,它的出鏡率十分高。還有ConfigureableListableBeanFactory,是他的直接子介面,實際上ConfigureableListableBeanFactory都間接或直接實現了這三個二級子介面。

2.HierarchicalBeanFactory 可分層次Bean工廠

(1)java doc

/**
 * Sub-interface implemented by bean factories that can be part
 * of a hierarchy.
 *
 * <p>The corresponding {@code setParentBeanFactory} method for bean
 * factories that allow setting the parent in a configurable
 * fashion can be found in the ConfigurableBeanFactory interface.

層次Bean工廠,從這個介面開始,BeanFactory有了雙親Factory,父Factory的概念。

(2)源碼

public interface HierarchicalBeanFactory extends BeanFactory {

    /**
     * Return the parent bean factory, or {@code null} if there is none.
     */
    BeanFactory getParentBeanFactory();

    /**
     * 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);

}

這個介面只是擴展了兩個方法,一個是可以獲取父工廠,返回值也是BeanFactory。

另外一個方法是判斷當前Factory是否包含給定名字的Bean,要註意的是這裡只是判斷當前工廠容器,而不管父輩,祖輩工廠。這也是分層思想的體現。

分層繼承,從此開始。

(3)繼承體系

HierarchicalBeanFactory繼承體系

好吧,這裡又出現DefaultListableBeanFactory了。

直接子介面共有兩個,一個是ApplicationContext,還有一個是ConfigurableBeanFactory。

3.ListableBeanFactory 可將Bean逐一列出的Bean工廠

(1)java doc

/**
 * Extension of the {@link BeanFactory} interface to be implemented by bean factories
 * that can enumerate all their bean instances, rather than attempting bean lookup
 * by name one by one as requested by clients. BeanFactory implementations that
 * preload all their bean definitions (such as XML-based factories) may implement
 * this interface.
 *
 * <p>If this is a {@link HierarchicalBeanFactory}, the return values will <i>not</i>
 * take any BeanFactory hierarchy into account, but will relate only to the beans
 * defined in the current factory. Use the {@link BeanFactoryUtils} helper class
 * to consider beans in ancestor factories too.
 *
 * <p>The methods in this interface will just respect bean definitions of this factory.
 * They will ignore any singleton beans that have been registered by other means like
 * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}'s
 * {@code registerSingleton} method, with the exception of
 * {@code getBeanNamesOfType} and {@code getBeansOfType} which will check
 * such manually registered singletons too. Of course, BeanFactory's {@code getBean}
 * does allow transparent access to such special beans as well. However, in typical
 * scenarios, all beans will be defined by external bean definitions anyway, so most
 * applications don't need to worry about this differentiation.
 *
 * <p><b>NOTE:</b> With the exception of {@code getBeanDefinitionCount}
 * and {@code containsBeanDefinition}, the methods in this interface
 * are not designed for frequent invocation. Implementations may be slow.
 */

總結一下:

1.從這個工廠介面開始,可以枚舉列出工廠可以生產的所有實例。

2. 而且如果是一個層次繼承的工廠,則只會列出當前工廠的實例,而不會列出祖先層的實例。

(2)源碼

public interface ListableBeanFactory extends BeanFactory {

    /**
     * Check if this bean factory contains a bean definition with the given name.
     * <p>Does not consider any hierarchy this factory may participate in,
     * and ignores any singleton beans that have been registered by
     * other means than bean definitions.
     */
    // 對於給定的名字是否含有BeanDefinition
    boolean containsBeanDefinition(String beanName);

    /**
     * Return the number of beans defined in the factory.
     * <p>Does not consider any hierarchy this factory may participate in,
     * and ignores any singleton beans that have been registered by
     * other means than bean definitions.
     */
    // 返回工廠的BeanDefinition總數
    int getBeanDefinitionCount();

    /**
     * Return the names of all beans defined in this factory.
     * <p>Does not consider any hierarchy this factory may participate in,
     * and ignores any singleton beans that have been registered by
     * other means than bean definitions.
     * @return the names of all beans defined in this factory,
     * or an empty array if none defined
     */
    // 返回工廠中所有BeanDefineition的名字
    String[] getBeanDefinitionNames();

    /**
     * Return the names of beans matching the given type (including subclasses),
     * judging from either bean definitions or the value of {@code getObjectType}
     * in the case of FactoryBeans.
     * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
     * check nested beans which might match the specified type as well.
     * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
     * will get initialized. If the object created by the FactoryBean doesn't match,
     * the raw FactoryBean itself will be matched against the type.
     * <p>Does not consider any hierarchy this factory may participate in.
     * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
     * to include beans in ancestor factories too.
     * <p>Note: Does <i>not</i> ignore singleton beans that have been registered
     * by other means than bean definitions.
     * <p>This version of {@code getBeanNamesForType} matches all kinds of beans,
     * be it singletons, prototypes, or FactoryBeans. In most implementations, the
     * result will be the same as for {@code getBeanNamesForType(type, true, true)}.
     * <p>Bean names returned by this method should always return bean names <i>in the
     * order of definition</i> in the backend configuration, as far as possible.
     * @param type the class or interface to match, or {@code null} for all bean names
     * @return the names of beans (or objects created by FactoryBeans) matching
     * the given object type (including subclasses), or an empty array if none
     * @see FactoryBean#getObjectType
     * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class)
     */
    //根據類型來返回Bean名稱,包含該層的所有Bean,包括FactoryBean
    String[] getBeanNamesForType(Class<?> type);

    /*
         * 返回指定類型的名字 includeNonSingletons為false表示只取單例Bean,true則不是
         * allowEagerInit為true表示立刻載入,false表示延遲載入。 註意:FactoryBeans都是立刻加    載的。
         */
    String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);

    //返回對應類型的Bean實例,鍵為Bean 名稱
    <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;

    
    <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
            throws BeansException;

    /**
     * Find all names of beans whose {@code Class} has the supplied {@link Annotation}
     * type, without creating any bean instances yet.
     * @param annotationType the type of annotation to look for
     * @return the names of all matching beans
     * @since 4.0
     */
    //根據註解類型返回對應的Bean名稱
    String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);

    //根據註解返回對應Bean 名稱,Bean實例Map
    Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

    /**
     * Find an {@link Annotation} of {@code annotationType} on the specified
     * bean, traversing its interfaces and super classes if no annotation can be
     * found on the given class itself.
    */
    //查找對應Bean名稱,對應註解類型的註解
    <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
            throws NoSuchBeanDefinitionException;

}

總結:

這個Bean介面總體來看是返回一組Bean名稱,或者一組Bean名稱,Bean實例的Map。同時還涉及到了返回BeanDefinition的方法。

值得註意的是BeanDefinition從這裡登場了開始。

 

(3)繼承體系

ListableBeanFactory繼承體系

又一次看到了DefaultListableBeanFactory介面。

四.整體體繫結構

是時候看看整體圖了,我當時是直接從《Spring 技術內幕》中看到這個圖的,當時就蒙圈了。現在整體走一遍再看,可能就好一些了。

BeanFactory介面

可以看到的是DefaultListBeanFactory參考

具體:

  1、BeanFactory作為一個主介面不繼承任何介面,暫且稱為一級介面

  2、有3個子介面繼承了它,進行功能上的增強。這3個子介面稱為二級介面

  3、ConfigurableBeanFactory可以被稱為三級介面,對二級介面HierarchicalBeanFactory進行了再次增強,它還繼承了另一個外來的介面SingletonBeanRegistry

  4、ConfigurableListableBeanFactory是一個更強大的介面,繼承了上述的所有介面,無所不包,稱為四級介面

  (這4級介面是BeanFactory的基本介面體系。繼續,下麵是繼承關係的2個抽象類和2個實現類:)

  5、AbstractBeanFactory作為一個抽象類,實現了三級介面ConfigurableBeanFactory大部分功能。

  6、AbstractAutowireCapableBeanFactory同樣是抽象類,繼承自AbstractBeanFactory,並額外實現了二級介面AutowireCapableBeanFactory

  7、DefaultListableBeanFactory繼承自AbstractAutowireCapableBeanFactory,實現了最強大的四級介面ConfigurableListableBeanFactory,並實現了一個外來介面 BeanDefinitionRegistry,它並非抽象類。

  8、最後是最強大的XmlBeanFactory,繼承自DefaultListableBeanFactory,重寫了一些功能,使自己更強大。提供了Xml文件相關BeanFactory的方法。可以讀取xml定義的BeanDefinition文件。

總結:XmlBeanFactory,只是提供了最基本的IOC容器的功能。而且XMLBeanFactory,繼承自DefaultListableBeanFactory。DefaultListableBeanFactory實際包含了基本IOC容器所具有的所有重要功能,是一個完整的IOC容器。

 

參考資料:

1.Spring:源碼解讀Spring IOC原理

2.Spring源碼分析——BeanFactory體系之介面詳細分析

3. spring IOC源碼分析(1)

4. 《Spring 技術內幕》強烈推薦


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 所有的外部輸入參數都應該檢查合法性。 未正確處理輸入數據將可能導致sql註入等漏洞。 框架提供系列函數來取$_REQUEST中的值 requestInt requestString requestFloat requestBool ps:註意$_REQUEST中變數類型可能會是數組 如請求為 ?i[
  • 一、函數的定義 用戶函數的定義從function 關鍵字開始,如下 function foo($var) { echo $var; } 1、詞法分析 在Zend/zend_language_scanner.l中我們找到如下所示的代碼: <ST_IN_SCRIPTING>"function" { re
  • 首先上一張出現問題的圖片: 出現這個問題一般是你的jdk和eclipse不是同一位的,比如你的jdk是32位的但是eclipse下載的是64位的就會導致這種問題。 解決方案:把兩者都換為32或者64位的即可。 如何查看自己的jdk版本?大家可以下載到自己設備運行(註意:一定要以管理員許可權運行),網址
  • 最近碰到一些 SSL 的小問題,特記錄下。 我們有個 Java 實現的 SSL TCP 服務端,為客戶端(PC、Android 和 iOS)提供 SSL 接入連接服務。最近有用戶反饋其手機上 App 不能正常連接登錄,別人手機上都可以。經過單獨回訪調查該用戶使用的手機操作系統是 Android 6.
  • 一、什麼是CocoaPods CocoaPods是iOS項目的依賴管理工具,該項目源碼在Github上管理。開發iOS項目不可避免地要使用第三方開源庫,CocoaPods的出現使得我們可以節省設置和第三方開源庫的時間。 在使用CocoaPods之前,開發項目需要用到第三方開源庫的時候,我們需要 1...
  • 問題沒有解決,屬於菜鳥級別的孩子~~~~ 求助啊,求助!!!!!! 報告如下: Warning:An unhandled exception occurred. Please report the problemusing the error reporting dialog or via emai
  • php的函數包括用戶定義的函數、內部函數(print_r count...)、匿名函數、變數函數($func = 'print_r'; $func(array('a','b'));) PHP內核源碼中將函數分為以下類型 #define ZEND_INTERNAL_FUNCTION 1 #define
  • 大型網站的優化技術:1,SEO,優化一種,2,頁面靜態化3,memcache(記憶體緩存)4,伺服器集群技術 總的目標:提高網站的訪問速度,SEO目的:提高網站的排名,(解決的是速度)SEO: google 的優化,百度的優化: 今天先從頁面靜態化來講:先講幾個概念:1,靜態網址純粹的html文檔ht
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...