首页 > 代码库 > spring beans源码解读之--BeanFactory

spring beans源码解读之--BeanFactory

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

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

 

     

      (来源eclipse)                                                                                    (来自http://www.myexception.cn/software-architecture-design/925888.html)

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容器的可定制性,它定义了设置类装载器、属性编辑器、容器初始化后置处理器等方法;

SingletonBeanRegistry:定义了允许在运行期间向容器注册单实例Bean的方法;

BeanDefinitionRegistry:Spring配置文件中每一个<bean>节点元素在Spring容器里都通过一个BeanDefinition对象表示,它描述了Bean的配置信息。而BeanDefinition Registry接口提供了向容器手工注册BeanDefinition对象的方法。

 

 

 

spring beans源码解读之--BeanFactory