spring源码解读-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定义文件。

  1. 通过setters,constructors进行依赖注入更好,其实这也是常用的方法
  2. BeanFactory通过载入配置源文件(XML文件)的方式,来配置Bean。
  3. 最后一大段是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作为最顶层的一个接口类,它定义了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)源码

/**
     * 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)继承体系

要注意看这个实现类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)继承体系

好吧,这里又出现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)继承体系

又一次看到了DefaultListableBeanFactory接口。

四.整体体系结构

是时候看看整体图了,我当时是直接从《Spring 技术内幕》中看到这个图的,当时就蒙圈了。现在整体走一遍再看,可能就好一些了。

可以看到的是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体系之接口详细分析

  1. spring IOC源码分析(1)
  2. 《Spring 技术内幕》强烈推荐

原文:https://www.cnblogs.com/ToBeAProgrammer/p/5192837.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,254评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,875评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,682评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,896评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,015评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,152评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,208评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,962评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,388评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,700评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,867评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,551评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,186评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,901评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,142评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,689评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,757评论 2 351