zoukankan      html  css  js  c++  java
  • spring beans源码解读之--BeanFactory进化史

    BeanFactory是访问bean容器的根接口,它是一个bean容器的基本客户端视图。

    先让我们看看beanfactory的前生后世吧!

                                                                                

    beanFactory有四个重要的子接口:

     SimpleJndiBeanFactory是spring beanFactory接口的基于jndi的简单实现。不支持枚举bean定义,故不需要实现ListableBeanFactory接口。这个bean工厂可以解析制定名称的jndi名称,在J2EE应用中,jndi名称的命名空间为"java:/comp/env/".

    这个bean工厂主要和spring的CommonAnnotationBeanPostProcessor 联合使用。

    The main intent of this factory is usage in combination with Spring's CommonAnnotationBeanPostProcessor, configured as "resourceFactory" for resolving @Resource annotations as JNDI objects without intermediate bean definitions. It may be used for similar lookup scenarios as well, of course, in particular if BeanFactory-style type checking is required.
    ListableBeanFactory是beanFactory接口的扩展接口,它可以枚举所有的bean实例,而不是客户端通过名称一个一个的查询得出所有的实例。要预加载所有的bean定义的beanfactory可以实现这个接口来。该 接口定义了访问容器中Bean基本信息的若干方法,如查看Bean的个数、获取某一类型Bean的配置名、查看容器中是否包括某一Bean等方法;
        /**
         * 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.
         * @param beanName the name of the bean to look for
         * @return if this bean factory contains a bean definition with the given name
         * @see #containsBean
         */
        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.
         * @return the number of beans defined in the factory
         */
        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
         */
        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 getBeanNamesOfType(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)
         */
        String[] getBeanNamesForType(Class<?> type);
    
        /**
         * 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 if the "allowEagerInit" flag is set,
         * 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. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
         * (which doesn't require initialization of each FactoryBean).
         * <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>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
         * @param includeNonSingletons whether to include prototype or scoped beans too
         * or just singletons (also applies to FactoryBeans)
         * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
         * <i>objects created by FactoryBeans</i> (or by factory methods with a
         * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
         * eagerly initialized to determine their type: So be aware that passing in "true"
         * for this flag will initialize FactoryBeans and "factory-bean" references.
         * @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, boolean, boolean)
         */
        String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
    
        /**
         * Return the bean instances that match the given object 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 beansOfTypeIncludingAncestors}
         * 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 getBeansOfType matches all kinds of beans, be it
         * singletons, prototypes, or FactoryBeans. In most implementations, the
         * result will be the same as for {@code getBeansOfType(type, true, true)}.
         * <p>The Map returned by this method should always return bean names and
         * corresponding bean instances <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 concrete beans
         * @return a Map with the matching beans, containing the bean names as
         * keys and the corresponding bean instances as values
         * @throws BeansException if a bean could not be created
         * @since 1.1.2
         * @see FactoryBean#getObjectType
         * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
         */
        <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;
    
        /**
         * Return the bean instances that match the given object 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 if the "allowEagerInit" flag is set,
         * 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. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
         * (which doesn't require initialization of each FactoryBean).
         * <p>Does not consider any hierarchy this factory may participate in.
         * Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors}
         * 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>The Map returned by this method should always return bean names and
         * corresponding bean instances <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 concrete beans
         * @param includeNonSingletons whether to include prototype or scoped beans too
         * or just singletons (also applies to FactoryBeans)
         * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
         * <i>objects created by FactoryBeans</i> (or by factory methods with a
         * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
         * eagerly initialized to determine their type: So be aware that passing in "true"
         * for this flag will initialize FactoryBeans and "factory-bean" references.
         * @return a Map with the matching beans, containing the bean names as
         * keys and the corresponding bean instances as values
         * @throws BeansException if a bean could not be created
         * @see FactoryBean#getObjectType
         * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
         */
        <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
         */
        String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);
    
        /**
         * Find all beans whose {@code Class} has the supplied {@link Annotation} type,
         * returning a Map of bean names with corresponding bean instances.
         * @param annotationType the type of annotation to look for
         * @return a Map with the matching beans, containing the bean names as
         * keys and the corresponding bean instances as values
         * @throws BeansException if a bean could not be created
         * @since 3.0
         */
        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.
         * @param beanName the name of the bean to look for annotations on
         * @param annotationType the annotation class to look for
         * @return the annotation of the given type if found, or {@code null}
         * @throws NoSuchBeanDefinitionException if there is no bean with the given name
         * @since 3.0
         */
        <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
                throws NoSuchBeanDefinitionException;
    HierarchicalBeanFactory 是一个bean factory 子接口实现,可以作为层次结构的一部分。相对应的bean Factory方法setParentBeanFactory允许在一个可配置beanfactory中设置它们的父bean factory。
        /**
         * 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);
    AutowireCapableBeanFactory:beanFactory接口的扩展实现,假如它们想要对已经存在的bean暴露它的功能,实现它就能实现自动装配功能。
    定义了将容器中的Bean按某种规则(如按名字匹配、按类型匹配等)进行自动装配的方法;
        /**
         * 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;
    
        /**
         * Constant that indicates autowiring the greediest constructor that
         * can be satisfied (involves resolving the appropriate constructor).
         * @see #createBean
         * @see #autowire
         */
        int AUTOWIRE_CONSTRUCTOR = 3;
    
        /**
         * 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;
    
    
        //-------------------------------------------------------------------------
        // 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.
         * @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;
    
        /**
         * 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.
         * @param existingBean the existing bean instance
         * @throws BeansException if wiring failed
         */
        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>
         * @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;
    
        /**
         * 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
         * @return the resolved object, or {@code null} if none found
         * @throws BeansException in dependency resolution failed
         */
        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.
         * @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;
    
        /**
         * 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;
    
        /**
         * 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;

    其中:

    HierarchicalBeanFactory的子接口
    
    ConfigurableBeanFactory是一个配置接口,大部分beanFactory实现了这个接口。这个接口提供了对一个beanfactory进行配置的便利方法,加上beanFactory接口的客户端方法。增强了IoC容器的可定制性,它定义了设置类装载器、属性编辑器、容器初始化后置处理器等方法;
    public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
    
        /**
         * Scope identifier for the standard singleton scope: "singleton".
         * Custom scopes can be added via {@code registerScope}.
         * @see #registerScope
         */
        String SCOPE_SINGLETON = "singleton";
    
        /**
         * Scope identifier for the standard prototype scope: "prototype".
         * Custom scopes can be added via {@code registerScope}.
         * @see #registerScope
         */
        String SCOPE_PROTOTYPE = "prototype";
    
    
        /**
         * Set the parent of this bean factory.
         * <p>Note that the parent cannot be changed: It should only be set outside
         * a constructor if it isn't available at the time of factory instantiation.
         * @param parentBeanFactory the parent BeanFactory
         * @throws IllegalStateException if this factory is already associated with
         * a parent BeanFactory
         * @see #getParentBeanFactory()
         */
        void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
    
        /**
         * Set the class loader to use for loading bean classes.
         * Default is the thread context class loader.
         * <p>Note that this class loader will only apply to bean definitions
         * that do not carry a resolved bean class yet. This is the case as of
         * Spring 2.0 by default: Bean definitions only carry bean class names,
         * to be resolved once the factory processes the bean definition.
         * @param beanClassLoader the class loader to use,
         * or {@code null} to suggest the default class loader
         */
        void setBeanClassLoader(ClassLoader beanClassLoader);
    
        /**
         * Return this factory's class loader for loading bean classes.
         */
        ClassLoader getBeanClassLoader();
    
        /**
         * Specify a temporary ClassLoader to use for type matching purposes.
         * Default is none, simply using the standard bean ClassLoader.
         * <p>A temporary ClassLoader is usually just specified if
         * <i>load-time weaving</i> is involved, to make sure that actual bean
         * classes are loaded as lazily as possible. The temporary loader is
         * then removed once the BeanFactory completes its bootstrap phase.
         * @since 2.5
         */
        void setTempClassLoader(ClassLoader tempClassLoader);
    
        /**
         * Return the temporary ClassLoader to use for type matching purposes,
         * if any.
         * @since 2.5
         */
        ClassLoader getTempClassLoader();
    
        /**
         * Set whether to cache bean metadata such as given bean definitions
         * (in merged fashion) and resolved bean classes. Default is on.
         * <p>Turn this flag off to enable hot-refreshing of bean definition objects
         * and in particular bean classes. If this flag is off, any creation of a bean
         * instance will re-query the bean class loader for newly resolved classes.
         */
        void setCacheBeanMetadata(boolean cacheBeanMetadata);
    
        /**
         * Return whether to cache bean metadata such as given bean definitions
         * (in merged fashion) and resolved bean classes.
         */
        boolean isCacheBeanMetadata();
    
        /**
         * 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(BeanExpressionResolver resolver);
    
        /**
         * Return the resolution strategy for expressions in bean definition values.
         * @since 3.0
         */
        BeanExpressionResolver getBeanExpressionResolver();
    
        /**
         * Specify a Spring 3.0 ConversionService to use for converting
         * property values, as an alternative to JavaBeans PropertyEditors.
         * @since 3.0
         */
        void setConversionService(ConversionService conversionService);
    
        /**
         * Return the associated ConversionService, if any.
         * @since 3.0
         */
        ConversionService getConversionService();
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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.
         * @see #addPropertyEditorRegistrar
         * @see #registerCustomEditor
         * @since 2.5
         */
        void setTypeConverter(TypeConverter typeConverter);
    
        /**
         * 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();
    
        /**
         * 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);
    
        /**
         * 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
         */
        String resolveEmbeddedValue(String value);
    
        /**
         * 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);
    
        /**
         * Return the current number of registered BeanPostProcessors, if any.
         */
        int getBeanPostProcessorCount();
    
        /**
         * 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);
    
        /**
         * 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();
    
        /**
         * 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
         */
        Scope getRegisteredScope(String scopeName);
    
        /**
         * Provides a security access control context relevant to this factory.
         * @return the applicable AccessControlContext (never {@code null})
         * @since 3.0
         */
        AccessControlContext getAccessControlContext();
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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;
    
        /**
         * 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;
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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);
    
        /**
         * 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();
    
    }

    ConfigurableListableBeanFactory 它同时继承了ListableBeanFactory,AutowireCapableBeanFactory和ConfigurableBeanFactory,提供了对bean定义的分析和修改的便利方法,同时也提供了对单例的预实例化。

    public interface ConfigurableListableBeanFactory
            extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
    
        /**
         * Ignore the given dependency type for autowiring:
         * for example, String. Default is none.
         * @param type the dependency type to ignore
         */
        void ignoreDependencyType(Class<?> type);
    
        /**
         * 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);
    
        /**
         * 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, Object autowiredValue);
    
        /**
         * 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;
    
        /**
         * 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;
    
        /**
         * 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();
    
        /**
         * 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();
    
        /**
         * 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;
    
    }

    小结:

    1. beanFactory有四个子接口,添加了四种不同的能力,分别是:

    SimpleJndiBeanFactory:支持jndi。

    AutowireCapableBeanFactory:支持自动装配。

    HierarchicalBeanFactory:支持层次结构,ConfigurableListableBeanFactory实现了HierarchicalBeanFactory,提供了可配置功能。

    ListableBeanFactory:支持枚举。

    2. bean经过两次进化,到了DefaultListableBeanFactory,完善了bean容器的功能。

       DefaultListableBeanFactory实现了AbstractAutowireCapableBeanFactory,ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable等多个接口。

    3.最终进化:

    XmlBeanFactory 通过从xml文件中读取bean的定义和依赖。

    下一节,重点了解AbstractAutowireCapableBeanFactory,BeanDefinitionRegistry接口,全面了解bean factory的完整进化历史。

    
    
    
    
    
    
    

     

  • 相关阅读:
    javaScript系列 [35]HTML页面渲染的基本过程
    javaScript系列 [29] RegExp
    javaScript系列 [40]defineProperty
    javaScript系列 [32] type
    javaScript系列 [34]FormData
    javaScript系列 [39]deepClone
    javaScript系列 [33] new
    javaScript系列 [36]Call by sharing
    javaScript系列 [38]浏览器、HTML和内核(引擎)
    javaScript系列 [28] Event
  • 原文地址:https://www.cnblogs.com/davidwang456/p/4152241.html
Copyright © 2011-2022 走看看