spring源码解读:BeanFactory接口

xiaoxiao2021-02-28  106

不知道为什么看着Spring的源码,感触最深的是Spring对概念的抽象,所以我就先学接口了,BeanFactory是Spring IOC实现的基础,这边定义了一系列的接口,我们通过这些接口的学习,可以大致了解BeanFactory体系各接口如何分工合作。

为学习具体实现打下基础.毕竟这边逻辑复杂,涉及的概念很多.

BeanFactory 是Spring bean容器的根接口.提供获取bean,是否包含bean,是否单例与原型,获取bean类型,bean 别名的api.

-- AutowireCapableBeanFactory 添加集成其他框架功能.如果集成WebWork则可以使用Spring对Actions等进行管理.

-- HierarchicalBeanFactory 提供父容器的访问功能

-- -- ConfigurableBeanFactory 如名,提供factory的配置功能,眼花缭乱好多api

-- -- -- ConfigurableListableBeanFactory 集大成者,提供解析,修改bean定义,并与初始化单例.

-- ListableBeanFactory 提供容器内bean实例的枚举功能.这边不会考虑父容器内的实例.

看到这边,我们是不是想起了设计模式原则里的接口隔离原则

 Interface Segregation Principle(ISP):客户端不应该依赖它不需要的接口;类间的依赖关系应该建立在最小的接口上

这边清晰地定义了如下的体系:

  根接口BeanFactory(基础容器)

  第二层: 第三方集成,继承体系,遍历bean

  第三层: 配置功能

  第四层: 配置+迭代

接下来具体分析下各个接口吧(顺便做目录):

1. BeanFactory

2. AutowireCapableBeanFactory

3. HierarchicalBeanFactory

4. ListableBeanFactory

5. ConfigurableBeanFactory

6. ConfigableListableBeanFactory

1.BeanFactory

BeanFactory是Spring bean容器的根接口.

每个bean都是通过string类型bean name进行标识.这边提供了设计模式单例,原型的替代实现.

如果bean name配置为单例,应用内只会获取到一个实例.如果配置为原型,那么可以实例化好后填充属性(基于用户的配置).

BeanFactory作为应用集中配置管理的地方,极大简便应用开发,这样开发人员可以集中与业务.

package org.springframework.beans.factory; import org.springframework.beans.BeansException; public interface BeanFactory { String FACTORY_BEAN_PREFIX = "&"; Object getBean(String name) throws BeansException; <T> T getBean(String name, Class<T> requiredType) throws BeansException; <T> T getBean(Class<T> requiredType) throws BeansException; Object getBean(String name, Object... args) throws BeansException; boolean containsBean(String name); boolean isSingleton(String name) throws NoSuchBeanDefinitionException; boolean isPrototype(String name) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException; Class<?> getType(String name) throws NoSuchBeanDefinitionException; String[] getAliases(String name); }

BeanFactory需要管理bean的生命周期,比如初始化时需要按顺序实现如下接口:

  1. BeanNameAware's {@code setBeanName}   2. BeanClassLoaderAware's {@code setBeanClassLoader}   3. BeanFactoryAware's {@code setBeanFactory}   4. ResourceLoaderAware's {@code setResourceLoader}仅对application context有效   5. ApplicationEventPublisherAware's {@code setApplicationEventPublisher}仅对application context有效   6. MessageSourceAware's {@code setMessageSource}仅对application context有效   7. ApplicationContextAware's {@code setApplicationContext}仅对application context有效   8. ServletContextAware's {@code setServletContext}仅对application context有效   9. {@code postProcessBeforeInitialization} methods of BeanPostProcessors   10. InitializingBean's {@code afterPropertiesSet}   11. a custom init-method definition xml中配置的init-method   12. {@code postProcessAfterInitialization} methods of BeanPostProcessors

还有关闭容器的接口:

  1. DisposableBean's {@code destroy}   2. a custom destroy-method definition xml配置中的destroy-method

接口里定义了一个变量String FACTORY_BEAN_PREFIX = "&";

这是用来区分是获取FactoryBean还是FactoryBean的createBean创建的实例.如果&开始则获取FactoryBean;否则获取createBean创建的实例.

我们来看下定义的方法:

  a, 获取bean,这边可以实现单例,原型

    Object getBean(String name) throws BeansException; 可以用别名查找哦

    <T> T getBean(String name, Class<T> requiredType) throws BeansException;

    <T> T getBean(Class<T> requiredType) throws BeansException; 这边的类型可以是接口或者子类,但不能是null

    Object getBean(String name, Object... args) throws BeansException;

  b, 判断是否包含bean.陷阱出现:这边不管类是否抽象类,懒加载,是否在容器范围内,只要符合都返回true,所以这边true,不一定能从getBean获取实例

    boolean containsBean(String name);

  c, 单例,原型,bean类型的判断

    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

    boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

    boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException;

  d, 获取bean 的类型,别名

    Class<?> getType(String name) throws NoSuchBeanDefinitionException;

    String[] getAliases(String name);

2. AutowireCapableBeanFactory

在BeanFactory基础上实现对已存在实例的管理.

可以使用这个接口集成其它框架,捆绑并填充并不由Spring管理生命周期并已存在的实例.像集成WebWork的Actions 和Tapestry Page就很实用.

一般应用开发者不会使用这个接口,所以像ApplicationContext这样的外观实现类不会实现这个接口,如果真手痒痒可以通过ApplicationContext的getAutowireCapableBeanFactory接口获取.

package org.springframework.beans.factory.config; import java.util.Set; import org.springframework.beans.BeansException; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanFactory; /** * 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. * * <p>Integration code for other frameworks can leverage this interface to * wire and populate existing bean instances that Spring does not control * the lifecycle of. This is particularly useful for WebWork Actions and * Tapestry Page objects, for example. * * <p>Note that this interface is not implemented by * {@link org.springframework.context.ApplicationContext} facades, * as it is hardly ever used by application code. That said, it is available * from an application context too, accessible through ApplicationContext's * {@link org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()} * method. * * <p>You may also implement the {@link org.springframework.beans.factory.BeanFactoryAware} * interface, which exposes the internal BeanFactory even when running in an * ApplicationContext, to get access to an AutowireCapableBeanFactory: * simply cast the passed-in BeanFactory to AutowireCapableBeanFactory. * * @author Juergen Hoeller * @since 04.12.2003 * @see org.springframework.beans.factory.BeanFactoryAware * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() */ public interface AutowireCapableBeanFactory extends BeanFactory { /** * 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</code> * and <code>setBeanFactory</code>, 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</code> 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</code> 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</code> 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</code> and <code>setBeanFactory</code>, * 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</code> 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</code> 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; /** * 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</code> if none found * @throws BeansException in dependency resolution failed */ Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException; }

这边定义了5种自动装配策略:不注入AUTOWIRE_NO,使用bean name策略装配AUTOWIRE_BY_NAME,使用类型装配策略AUTOWIRE_BY_TYPE,使用构造器装配策略AUTOWIRE_CONSTRUCTOR,自动装配策略AUTOWIRE_AUTODETECT

  这边的自动策略是先尝试构造器,然后才是byType.这边应该是跟xml配置文件中的装配策略对应.

继续看定义的api:

  a, 创建和填充外部bean实例的典型方法

    <T> T createBean(Class<T> beanClass) throws BeansException;

    void autowireBean(Object existingBean) throws BeansException; // 使用autowireBeanProperties装配属性

    Object configureBean(Object existingBean, String beanName) throws BeansException; // 自动装配属性,填充属性值,使用诸如setBeanName,setBeanFactory这样的工厂回调填充属性,最好还要调用post processor

    Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException;

  b, 在bean的生命周期进行细粒度控制的专门方法

    Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; // 会执行bean完整的初始化,包括BeanPostProcessors和initializeBean

    Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

    void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException;

    void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;

    Object initializeBean(Object existingBean, String beanName) throws BeansException;

    Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException;

    Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException;

    Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;

3. HierarchicalBeanFactory

 提供父容器的访问功能.至于父容器的设置,需要找ConfigurableBeanFactory的setParentBeanFactory(接口把设置跟获取给拆开了!).

package org.springframework.beans.factory; /** * Sub-interface implemented by bean factories that can be part * of a hierarchy. * * <p>The corresponding <code>setParentBeanFactory</code> method for bean * factories that allow setting the parent in a configurable * fashion can be found in the ConfigurableBeanFactory interface. * * @author Rod Johnson * @author Juergen Hoeller * @since 07.07.2003 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setParentBeanFactory */ public interface HierarchicalBeanFactory extends BeanFactory { /** * Return the parent bean factory, or <code>null</code> 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</code>, 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 org.springframework.beans.factory.BeanFactory#containsBean */ boolean containsLocalBean(String name); }

这边可说的不多,直接上api:

  a, 获取父容器 bean factory

    BeanFactory getParentBeanFactory();

  b, 判断当前容器是否保护bean

    boolean containsLocalBean(String name);

4. ListableBeanFactory

获取bean时,Spring 鼓励使用这个接口定义的api. 还有个Beanfactory方便使用.其他的4个接口都是不鼓励使用的.

提供容器中bean迭代的功能,不再需要一个个bean地查找.比如可以一次获取全部的bean(太暴力了),根据类型获取bean.在看SpringMVC时,扫描包路径下的具体实现策略就是使用的这种方式(那边使用的是BeanFactoryUtils封装的api).

 如果同时实现了HierarchicalBeanFactory,返回值不会考虑父类BeanFactory,只考虑当前factory定义的类.当然也可以使用BeanFactoryUtils辅助类来查找祖先工厂中的类. 

 这个接口中的方法只会考虑本factory定义的bean.这些方法会忽略ConfigurableBeanFactory的registerSingleton注册的单例bean(getBeanNamesOfType和getBeansOfType是例外,一样会考虑手动注册的单例).当然BeanFactory的getBean一样可以透明访问这些特殊bean.当然在典型情况下,所有的bean都是由external bean定义,所以应用不需要顾虑这些差别.

注意:getBeanDefinitionCount和containsBeanDefinition的实现方法因为效率比较低,还是少用为好.

package org.springframework.beans.factory; import java.lang.annotation.Annotation; import java.util.Map; import org.springframework.beans.BeansException; /** * 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</code> method, with the exception of * <code>getBeanNamesOfType</code> and <code>getBeansOfType</code> which will check * such manually registered singletons too. Of course, BeanFactory's <code>getBean</code> * 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 differentation. * * <p><b>NOTE:</b> With the exception of <code>getBeanDefinitionCount</code> * and <code>containsBeanDefinition</code>, the methods in this interface * are not designed for frequent invocation. Implementations may be slow. * * @author Rod Johnson * @author Juergen Hoeller * @since 16 April 2001 * @see HierarchicalBeanFactory * @see BeanFactoryUtils */ 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. * @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</code> * 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</code> * 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</code> 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)</code>. * <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</code> 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</code> * 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</code> * 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</code> 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</code> 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</code> * 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)</code>. * <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</code> 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</code> 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</code> * 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</code> 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 beans whose <code>Class</code> has the supplied {@link java.lang.annotation.Annotation} type. * @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 */ Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException; /** * Find a {@link Annotation} of <code>annotationType</code> 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 found, or <code>null</code> */ <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType); }

继续上api吧

  a, 暴力获取全部bean的属性:

    boolean containsBeanDefinition(String beanName);  //是否包含bean

    int getBeanDefinitionCount(); // 当前factory中定义的bean数量

    String[] getBeanDefinitionNames(); // 获取当前工厂中定义的所有bean 的name

  b, 根据bean 的类型获取bean

    这边的方法仅检查顶级bean.它不会检查嵌套的bean.FactoryBean创建的bean会匹配为FactoryBean而不是原始类型.

    一样不会考虑父factory中的bean,非要用可以通过BeanFactoryUtils中的beanNamesForTypeIncludingAncestors.     其他方式注册的单例这边会纳入判断.     这个版本的getBeanNamesForType会匹配所有类型的bean,包括单例,原型,FactoryBean.返回的bean names会根据backend 配置的进行排序.

    String[] getBeanNamesForType(Class<?> type); // 获取给定类型的bean names(包括子类),通过bean 定义或者FactoryBean的getObjectType判断.

    String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);

    <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException; // 如果保护懒加载的类,FactoryBean初始化的类和工厂方法初始化的类会被初始化.就是说执行这个方法会执行对应的初始化.

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

  c, 查找使用注解的类

    Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

  d, 查找一个类上的注解,如果找不到,父类,接口使用注解也算.

    <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType);

5. ConfigurableBeanFactory

定义BeanFactory的配置.

这边定义了太多太多的api,比如类加载器,类型转化,属性编辑器,BeanPostProcessor,作用域,bean定义,处理bean依赖关系,合并其他ConfigurableBeanFactory,bean如何销毁.

package org.springframework.beans.factory.config; import java.beans.PropertyEditor; import java.security.AccessControlContext; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.HierarchicalBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.core.convert.ConversionService; import org.springframework.util.StringValueResolver; /** * Configuration interface to be implemented by most bean factories. Provides * facilities to configure a bean factory, in addition to the bean factory * client methods in the {@link org.springframework.beans.factory.BeanFactory} * interface. * * <p>This bean factory interface 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 * needs. This extended interface is just meant to allow for framework-internal * plug'n'play and for special access to bean factory configuration methods. * * @author Juergen Hoeller * @since 03.11.2003 * @see org.springframework.beans.factory.BeanFactory * @see org.springframework.beans.factory.ListableBeanFactory * @see ConfigurableListableBeanFactory */ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry { /** * Scope identifier for the standard singleton scope: "singleton". * Custom scopes can be added via <code>registerScope</code>. * @see #registerScope */ String SCOPE_SINGLETON = "singleton"; /** * Scope identifier for the standard prototype scope: "prototype". * Custom scopes can be added via <code>registerScope</code>. * @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</code> 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</code> 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</code>) * @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</code> 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 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(); }

定义了两个作用域: 单例和原型.可以通过registerScope来添加.

  SCOPE_SINGLETON,SCOPE_PROTOTYPE

这边定义了好多好多的api,所以我们这边只讲业务,具体的api看文末的附录吧:

  a, 父容器设置.而且一旦设置了就不让修改

  b, 类加载器设置与获取.默认使用当前线程中的类加载器

  c, 为了类型匹配,搞个临时类加载器.好在一般情况为null,使用上面定义的标准加载器  

  d, 是否需要缓存bean metadata,比如bean difinition 和 解析好的classes.默认开启缓存

  e, 定义用于解析bean definition的表达式解析器

  f, 类型转化器

  g, 属性编辑器

  h, BeanFactory用来转换bean属性值或者参数值的自定义转换器

  i,string值解析器(想起mvc中的ArgumentResolver了)

  j,大boss BeanPostProcessor用于增强bean初始化功能 

  k,作用域定义

  l,访问权限控制

  m, 合并其他ConfigurableBeanFactory的配置,包括上面说到的BeanPostProcessor,作用域等

  n, bean定义处理

  o, bean创建状态控制.在解决循环依赖时有使用

  p, 处理bean依赖问题

  q, bean生命周期管理-- 销毁bean

--ConfigureableBeanFactory中定义的api:

  a, 父容器设置.而且一旦设置了就不让修改

    void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;

  b, 类加载器设置与获取.默认使用当前线程中的类加载器

    void setBeanClassLoader(ClassLoader beanClassLoader);

    ClassLoader getBeanClassLoader();

  c, 为了类型匹配,搞个临时类加载器.好在一般情况为null,使用上面定义的标准加载器  

    void setTempClassLoader(ClassLoader tempClassLoader);

    ClassLoader getTempClassLoader();

  d, 是否需要缓存bean metadata,比如bean difinition 和 解析好的classes.默认开启缓存

    void setCacheBeanMetadata(boolean cacheBeanMetadata);

    boolean isCacheBeanMetadata();

  e, 定义用于解析bean definition的表达式解析器

    void setBeanExpressionResolver(BeanExpressionResolver resolver);

    BeanExpressionResolver getBeanExpressionResolver();

  f, 类型转化器

    void setConversionService(ConversionService conversionService);

    ConversionService getConversionService();

  g, 属性编辑器

    void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);

    void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);

    void copyRegisteredEditorsTo(PropertyEditorRegistry registry);

  h, BeanFactory用来转换bean属性值或者参数值的自定义转换器

    void setTypeConverter(TypeConverter typeConverter);

    TypeConverter getTypeConverter();

  i,string值解析器(想起mvc中的ArgumentResolver了)

    void addEmbeddedValueResolver(StringValueResolver valueResolver);

    String resolveEmbeddedValue(String value);

  j,大boss BeanPostProcessor用于增强bean初始化功能

    void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

    int getBeanPostProcessorCount();    

  k,作用域定义

    void registerScope(String scopeName, Scope scope);

    String[] getRegisteredScopeNames();

    Scope getRegisteredScope(String scopeName);

  l,访问权限控制

    AccessControlContext getAccessControlContext();

  m, 合并其他ConfigurableBeanFactory的配置,包括上面说到的BeanPostProcessor,作用域等

    void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);

  n, bean定义处理

    void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; // 注册别名

    void resolveAliases(StringValueResolver valueResolver);

    BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; // 合并bean定义,包括父容器的

    boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; // 是否是FactoryBean类型

  o, bean创建状态控制.在解决循环依赖时有使用

    void setCurrentlyInCreation(String beanName, boolean inCreation);

    boolean isCurrentlyInCreation(String beanName);

  p, 处理bean依赖问题

    void registerDependentBean(String beanName, String dependentBeanName);

    String[] getDependentBeans(String beanName);

    String[] getDependenciesForBean(String beanName);

  q, bean生命周期管理-- 销毁bean

    void destroyBean(String beanName, Object beanInstance);

    void destroyScopedBean(String beanName);

    void destroySingletons();

6. ConfigableListableBeanFactory

 提供bean definition的解析,注册功能,再对单例来个预加载(解决循环依赖问题). 

貌似我们一般开发就会直接定义这么个接口了事.而不是像Spring这样先根据使用情况细分那么多,到这边再合并

package org.springframework.beans.factory.config; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; /** * Configuration interface to be implemented by most listable bean factories. * In addition to {@link ConfigurableBeanFactory}, it provides facilities to * analyze and modify bean definitions, and to pre-instantiate singletons. * * <p>This subinterface of {@link org.springframework.beans.factory.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. This interface is just meant to allow for framework-internal * plug'n'play even when needing access to bean factory configuration methods. * * @author Juergen Hoeller * @since 03.11.2003 * @see org.springframework.context.support.AbstractApplicationContext#getBeanFactory() */ 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</code> 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; } a, 设置忽略的依赖关系,注册找到的特殊依赖

    void ignoreDependencyType(Class<?> type); // 忽略类型

    void ignoreDependencyInterface(Class<?> ifc); // 忽略接口

    void registerResolvableDependency(Class<?> dependencyType, Object autowiredValue);

    boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) throws NoSuchBeanDefinitionException;

  b, 获取bean定义 (可以访问属性值跟构造方法的参数值)

    BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

  c, 锁定配置信息.在调用refresh时会使用到.

    void freezeConfiguration();

    boolean isConfigurationFrozen();

  d, 预加载不是懒加载的单例.用于解决循环依赖问题

    void preInstantiateSingletons() throws BeansException;

转载请注明原文地址: https://www.6miu.com/read-35544.html

最新回复(0)