一.BeanFactory

  BeanFactory是Spring IOC容器的基础,是IOC容器的基础接口,所有的容器都是从它这里继承实现而来。BeanFactory提供了最基本的IOC容器的功能,即所有的容器至少需要实现的标准。BeanFactory体系结构是典型的工厂方法模式,即什么样的工厂生产什么样的产品。BeanFactory是最基本的抽象工厂,而其他的IOC容器只不过是具体的工厂,对应着各自的Bean定义方法。但同时,其他容器也针对具体场景不同,进行了扩充,提供具体的服务。

二.BeanFacory源码

1.java doc

  首先是Java doc,现在阅读源码的习惯是一定要理解了java doc的描述,因为这里是作者的描述,没有人比作者更明白这个类,这个接口要干什么。

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

  在BeanFactory里只对IOC容器的基本行为作了定义,根本不关心你的bean是如何定义怎样加载的。正如我们只关心工厂里得到什么的产品对象,至于工厂是怎么生产这些对象的,这个基本的接口不关心。

2.源码

  1. public interface BeanFactory {
  2. /**
  3. * Used to dereference a {@link FactoryBean} instance and distinguish it from
  4. * beans <i>created</i> by the FactoryBean. For example, if the bean named
  5. * {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
  6. * will return the factory, not the instance returned by the factory.
  7. */
  8. //使用转义符&来得到FactoryBean本身,用来区分通过容器获得FactoryBean本身和其产生的对象
  9. String FACTORY_BEAN_PREFIX = "&";
  10.  
  11. //通过name来获取指定的bean
  12. Object getBean(String name) throws BeansException;
  13.  
  14. //根据名字和类型来得到bean实例,增加了类型安全验证机制
  15. <T> T getBean(String name, Class<T> requiredType) throws BeansException;
  16.  
  17. //通过类型获取bean实例
  18. <T> T getBean(Class<T> requiredType) throws BeansException;
  19.  
  20. //增加更多获取的条件,同上方法
  21. Object getBean(String name, Object... args) throws BeansException;
  22.  
  23. <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
  24.  
  25. //判断容器是否含有指定名字的bean
  26. boolean containsBean(String name);
  27.  
  28. //查询指定名字的Bean是不是单例的Bean
  29. boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
  30.  
  31. //判断Bean是不是prototype类型的bean
  32. boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
  33.  
  34. //查询指定了名字的Bean的Class类型是否与指定类型匹配
  35. boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException;
  36.  
  37. //获取指定名字bean的Class类型
  38. Class<?> getType(String name) throws NoSuchBeanDefinitionException;
  39.  
  40. //查询指定了名字的bean的所有别名,这些别名都是在BeanDefinition中定义的
  41. String[] getAliases(String name);
  42. }

  BeanFactory接口定义了IOC容器要实现的基本方法。

三. BeanFactory 结构体系

  其中BeanFactory作为最顶层的一个接口类,它定义了IOC容器的基本功能规范,BeanFactory 三个子类:ListableBeanFactory、HierarchicalBeanFactory和AutowireCapableBeanFactory。但是从上图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory,他实现了所有的接口。那为何要定义这么多层次的接口呢?查阅这些接口的源码和说明发现,每个接口都有他使用的场合,它主要是为了区分在 Spring 内部在操作过程中对象的传递和转化过程中,对对象的数据访问所做的限制。例如 ListableBeanFactory 接口表示这些 Bean是可列表的,而 HierarchicalBeanFactory 表示的是这些 Bean 是有继承关系的,也就是每个Bean有可能有父Bean。AutowireCapableBeanFactory 接口定义Bean的自动装配规则。这四个接口共同定义了Bean的集合、Bean之间的关系、以 Bean行为.

1.AutowireCapableBeanFactory

1.1Java doc文档

  1. /**
  2. * Extension of the {@link org.springframework.beans.factory.BeanFactory}
  3. * interface to be implemented by bean factories that are capable of
  4. autowiring, provided that they want to expose this functionality for
  5. * existing bean instances.
  6. *
  7. * <p>This subinterface of BeanFactory is not meant to be used in normal
  8. * application code: stick to {@link org.springframework.beans.factory.BeanFactory}
  9. * or {@link org.springframework.beans.factory.ListableBeanFactory} for
  10. * typical use cases.
  11. *
  12. * <p>Integration code for other frameworks can leverage this interface to
  13. * wire and populate existing bean instances that Spring does not control
  14. * the lifecycle of. This is particularly useful for WebWork Actions and
  15. * Tapestry Page objects, for example.
  16. *
  17. * <p>Note that this interface is not implemented by
  18. * {@link org.springframework.context.ApplicationContext} facades,
  19. * as it is hardly ever used by application code. That said, it is available
  20. * from an application context too, accessible through ApplicationContext's
  21. * {@link org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()}
  22. * method.
  23. *
  24. * <p>You may also implement the {@link org.springframework.beans.factory.BeanFactoryAware}
  25. * interface, which exposes the internal BeanFactory even when running in an
  26. * ApplicationContext, to get access to an AutowireCapableBeanFactory:
  27. * simply cast the passed-in BeanFactory to AutowireCapableBeanFactory.
  28. org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
  29. */

  这个工厂接口继承自BeanFacotory,它扩展了自动装配的功能,根据类定义BeanDefinition装配Bean、执行前、后处理器等。主要用它来管理ApplicationContext所不能管理的那些Bean,比如Filter,Servlet等。主要通过ApplicationContext的getAutowireCapableBeanFactory()获得实例。

1.2源码

  1. public interface AutowireCapableBeanFactory extends BeanFactory {
  2.  
  3. /**
  4. * Constant that indicates no externally defined autowiring. Note that
  5. * BeanFactoryAware etc and annotation-driven injection will still be applied.
  6. * @see #createBean
  7. * @see #autowire
  8. * @see #autowireBeanProperties
  9. */
  10. int AUTOWIRE_NO = 0;
  11.  
  12. /**
  13. * Constant that indicates autowiring bean properties by name
  14. * (applying to all bean property setters).
  15. * @see #createBean
  16. * @see #autowire
  17. * @see #autowireBeanProperties
  18. */
  19. int AUTOWIRE_BY_NAME = 1;
  20.  
  21. /**
  22. * Constant that indicates autowiring bean properties by type
  23. * (applying to all bean property setters).
  24. * @see #createBean
  25. * @see #autowire
  26. * @see #autowireBeanProperties
  27. */
  28. int AUTOWIRE_BY_TYPE = 2;
  29.  
  30. /**
  31. * Constant that indicates autowiring the greediest constructor that
  32. * can be satisfied (involves resolving the appropriate constructor).
  33. * @see #createBean
  34. * @see #autowire
  35. */
  36. int AUTOWIRE_CONSTRUCTOR = 3;
  37.  
  38. /**
  39. * Constant that indicates determining an appropriate autowire strategy
  40. * through introspection of the bean class.
  41. * @see #createBean
  42. * @see #autowire
  43. * @deprecated as of Spring 3.0: If you are using mixed autowiring strategies,
  44. * prefer annotation-based autowiring for clearer demarcation of autowiring needs.
  45. */
  46. @Deprecated
  47. int AUTOWIRE_AUTODETECT = 4;
  48.  
  49. //-------------------------------------------------------------------------
  50. // Typical methods for creating and populating external bean instances
  51. //-------------------------------------------------------------------------
  52.  
  53. /**
  54. * Fully create a new bean instance of the given class.
  55. * <p>Performs full initialization of the bean, including all applicable
  56. * {@link BeanPostProcessor BeanPostProcessors}.
  57. * <p>Note: This is intended for creating a fresh instance, populating annotated
  58. * fields and methods as well as applying all standard bean initialiation callbacks.
  59. * It does <i>not</> imply traditional by-name or by-type autowiring of properties;
  60. * use {@link #createBean(Class, int, boolean)} for that purposes.
  61. * @param beanClass the class of the bean to create
  62. * @return the new bean instance
  63. * @throws BeansException if instantiation or wiring failed
  64. */
  65. <T> T createBean(Class<T> beanClass) throws BeansException;
  66.  
  67. /**
  68. * Populate the given bean instance through applying after-instantiation callbacks
  69. * and bean property post-processing (e.g. for annotation-driven injection).
  70. * <p>Note: This is essentially intended for (re-)populating annotated fields and
  71. * methods, either for new instances or for deserialized instances. It does
  72. * <i>not</i> imply traditional by-name or by-type autowiring of properties;
  73. * use {@link #autowireBeanProperties} for that purposes.
  74. * @param existingBean the existing bean instance
  75. * @throws BeansException if wiring failed
  76. */
  77. void autowireBean(Object existingBean) throws BeansException;
  78.  
  79. /**
  80. * Configure the given raw bean: autowiring bean properties, applying
  81. * bean property values, applying factory callbacks such as {@code setBeanName}
  82. * and {@code setBeanFactory}, and also applying all bean post processors
  83. * (including ones which might wrap the given raw bean).
  84. * <p>This is effectively a superset of what {@link #initializeBean} provides,
  85. * fully applying the configuration specified by the corresponding bean definition.
  86. * <b>Note: This method requires a bean definition for the given name!</b>
  87. * @param existingBean the existing bean instance
  88. * @param beanName the name of the bean, to be passed to it if necessary
  89. * (a bean definition of that name has to be available)
  90. * @return the bean instance to use, either the original or a wrapped one
  91. * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
  92. * if there is no bean definition with the given name
  93. * @throws BeansException if the initialization failed
  94. * @see #initializeBean
  95. */
  96. Object configureBean(Object existingBean, String beanName) throws BeansException;
  97.  
  98. /**
  99. * Resolve the specified dependency against the beans defined in this factory.
  100. * @param descriptor the descriptor for the dependency
  101. * @param beanName the name of the bean which declares the present dependency
  102. * @return the resolved object, or {@code null} if none found
  103. * @throws BeansException in dependency resolution failed
  104. */
  105. Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException;
  106.  
  107. //-------------------------------------------------------------------------
  108. // Specialized methods for fine-grained control over the bean lifecycle
  109. //-------------------------------------------------------------------------
  110.  
  111. /**
  112. * Fully create a new bean instance of the given class with the specified
  113. * autowire strategy. All constants defined in this interface are supported here.
  114. * <p>Performs full initialization of the bean, including all applicable
  115. * {@link BeanPostProcessor BeanPostProcessors}. This is effectively a superset
  116. * of what {@link #autowire} provides, adding {@link #initializeBean} behavior.
  117. * @param beanClass the class of the bean to create
  118. * @param autowireMode by name or type, using the constants in this interface
  119. * @param dependencyCheck whether to perform a dependency check for objects
  120. * (not applicable to autowiring a constructor, thus ignored there)
  121. * @return the new bean instance
  122. * @throws BeansException if instantiation or wiring failed
  123. * @see #AUTOWIRE_NO
  124. * @see #AUTOWIRE_BY_NAME
  125. * @see #AUTOWIRE_BY_TYPE
  126. * @see #AUTOWIRE_CONSTRUCTOR
  127. */
  128. Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
  129.  
  130. /**
  131. * Instantiate a new bean instance of the given class with the specified autowire
  132. * strategy. All constants defined in this interface are supported here.
  133. * Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
  134. * before-instantiation callbacks (e.g. for annotation-driven injection).
  135. * <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
  136. * callbacks or perform any further initialization of the bean. This interface
  137. * offers distinct, fine-grained operations for those purposes, for example
  138. * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
  139. * callbacks are applied, if applicable to the construction of the instance.
  140. * @param beanClass the class of the bean to instantiate
  141. * @param autowireMode by name or type, using the constants in this interface
  142. * @param dependencyCheck whether to perform a dependency check for object
  143. * references in the bean instance (not applicable to autowiring a constructor,
  144. * thus ignored there)
  145. * @return the new bean instance
  146. * @throws BeansException if instantiation or wiring failed
  147. * @see #AUTOWIRE_NO
  148. * @see #AUTOWIRE_BY_NAME
  149. * @see #AUTOWIRE_BY_TYPE
  150. * @see #AUTOWIRE_CONSTRUCTOR
  151. * @see #AUTOWIRE_AUTODETECT
  152. * @see #initializeBean
  153. * @see #applyBeanPostProcessorsBeforeInitialization
  154. * @see #applyBeanPostProcessorsAfterInitialization
  155. */
  156. Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
  157.  
  158. /**
  159. * Autowire the bean properties of the given bean instance by name or type.
  160. * Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
  161. * after-instantiation callbacks (e.g. for annotation-driven injection).
  162. * <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
  163. * callbacks or perform any further initialization of the bean. This interface
  164. * offers distinct, fine-grained operations for those purposes, for example
  165. * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
  166. * callbacks are applied, if applicable to the configuration of the instance.
  167. * @param existingBean the existing bean instance
  168. * @param autowireMode by name or type, using the constants in this interface
  169. * @param dependencyCheck whether to perform a dependency check for object
  170. * references in the bean instance
  171. * @throws BeansException if wiring failed
  172. * @see #AUTOWIRE_BY_NAME
  173. * @see #AUTOWIRE_BY_TYPE
  174. * @see #AUTOWIRE_NO
  175. */
  176. void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
  177. throws BeansException;
  178.  
  179. /**
  180. * Apply the property values of the bean definition with the given name to
  181. * the given bean instance. The bean definition can either define a fully
  182. * self-contained bean, reusing its property values, or just property values
  183. * meant to be used for existing bean instances.
  184. * <p>This method does <i>not</i> autowire bean properties; it just applies
  185. * explicitly defined property values. Use the {@link #autowireBeanProperties}
  186. * method to autowire an existing bean instance.
  187. * <b>Note: This method requires a bean definition for the given name!</b>
  188. * <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
  189. * callbacks or perform any further initialization of the bean. This interface
  190. * offers distinct, fine-grained operations for those purposes, for example
  191. * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
  192. * callbacks are applied, if applicable to the configuration of the instance.
  193. * @param existingBean the existing bean instance
  194. * @param beanName the name of the bean definition in the bean factory
  195. * (a bean definition of that name has to be available)
  196. * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
  197. * if there is no bean definition with the given name
  198. * @throws BeansException if applying the property values failed
  199. * @see #autowireBeanProperties
  200. */
  201. void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;
  202.  
  203. /**
  204. * Initialize the given raw bean, applying factory callbacks
  205. * such as {@code setBeanName} and {@code setBeanFactory},
  206. * also applying all bean post processors (including ones which
  207. * might wrap the given raw bean).
  208. * <p>Note that no bean definition of the given name has to exist
  209. * in the bean factory. The passed-in bean name will simply be used
  210. * for callbacks but not checked against the registered bean definitions.
  211. * @param existingBean the existing bean instance
  212. * @param beanName the name of the bean, to be passed to it if necessary
  213. * (only passed to {@link BeanPostProcessor BeanPostProcessors})
  214. * @return the bean instance to use, either the original or a wrapped one
  215. * @throws BeansException if the initialization failed
  216. */
  217. Object initializeBean(Object existingBean, String beanName) throws BeansException;
  218.  
  219. /**
  220. * Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean
  221. * instance, invoking their {@code postProcessBeforeInitialization} methods.
  222. * The returned bean instance may be a wrapper around the original.
  223. * @param existingBean the new bean instance
  224. * @param beanName the name of the bean
  225. * @return the bean instance to use, either the original or a wrapped one
  226. * @throws BeansException if any post-processing failed
  227. * @see BeanPostProcessor#postProcessBeforeInitialization
  228. */
  229. Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  230. throws BeansException;
  231.  
  232. /**
  233. * Apply {@link BeanPostProcessor BeanPostProcessors} to the given existing bean
  234. * instance, invoking their {@code postProcessAfterInitialization} methods.
  235. * The returned bean instance may be a wrapper around the original.
  236. * @param existingBean the new bean instance
  237. * @param beanName the name of the bean
  238. * @return the bean instance to use, either the original or a wrapped one
  239. * @throws BeansException if any post-processing failed
  240. * @see BeanPostProcessor#postProcessAfterInitialization
  241. */
  242. Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
  243. throws BeansException;
  244.  
  245. /**
  246. * Destroy the given bean instance (typically coming from {@link #createBean}),
  247. * applying the {@link org.springframework.beans.factory.DisposableBean} contract as well as
  248. * registered {@link DestructionAwareBeanPostProcessor DestructionAwareBeanPostProcessors}.
  249. * <p>Any exception that arises during destruction should be caught
  250. * and logged instead of propagated to the caller of this method.
  251. * @param existingBean the bean instance to destroy
  252. */
  253. void destroyBean(Object existingBean);
  254.  
  255. /**
  256. * Resolve the specified dependency against the beans defined in this factory.
  257. * @param descriptor the descriptor for the dependency
  258. * @param beanName the name of the bean which declares the present dependency
  259. * @param autowiredBeanNames a Set that all names of autowired beans (used for
  260. * resolving the present dependency) are supposed to be added to
  261. * @param typeConverter the TypeConverter to use for populating arrays and
  262. * collections
  263. * @return the resolved object, or {@code null} if none found
  264. * @throws BeansException in dependency resolution failed
  265. */
  266. Object resolveDependency(DependencyDescriptor descriptor, String beanName,
  267. Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException;
  268.  
  269. }

1.首先几个属性,是装配策略

  AUTOWIRE_BY_NAME:根据名称记性装配。

  AUTOWIRE_BY_TYPE:根据类型进行装配。

  AUTOWIRE_BY_CONSTRUCT:使用构造函数进行装配。

2.重点关注两类方法

  Typical methods for creating and populating external bean instances。:用于创建和填充外部bean实例的典型方法

  Specialized methods for fine-grained control over the bean lifecycle。专门针对bean生命周期细粒度控制的方法

2.HierarchicalBeanFactory

2.1 JAVA DOC

  1. package org.springframework.beans.factory;
  2.  
  3. /**
  4. * Sub-interface implemented by bean factories that can be part
  5. * of a hierarchy.
  6. *
  7. * <p>The corresponding {@code setParentBeanFactory} method for bean
  8. * factories that allow setting the parent in a configurable
  9. * fashion can be found in the ConfigurableBeanFactory interface.
  10. public interface HierarchicalBeanFactory extends BeanFactory {
  11. /**
  12. * Return the parent bean factory, or {@code null} if there is none.
  13. */
  14. BeanFactory getParentBeanFactory();
  15.  
  16. /**
  17. * Return whether the local bean factory contains a bean of the given name,
  18. * ignoring beans defined in ancestor contexts.
  19. * <p>This is an alternative to {@code containsBean}, ignoring a bean
  20. * of the given name from an ancestor bean factory.
  21. * @param name the name of the bean to query
  22. * @return whether a bean with the given name is defined in the local factory
  23. * @see BeanFactory#containsBean
  24. */
  25. boolean containsLocalBean(String name);
  26. }

3.ListableBeanFactory

3.1JAVA DOC

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

总结一下:

  1.从这个工厂接口开始,可以枚举列出工厂可以生产的所有实例。

  2. 而且如果是一个层次继承的工厂,则只会列出当前工厂的实例,而不会列出祖先层的实例。

3.2源码

  1. public interface ListableBeanFactory extends BeanFactory {
  2. /**
  3. * Check if this bean factory contains a bean definition with the given name.
  4. * <p>Does not consider any hierarchy this factory may participate in,
  5. * and ignores any singleton beans that have been registered by
  6. * other means than bean definitions.
  7. * @param beanName the name of the bean to look for
  8. * @return if this bean factory contains a bean definition with the given name
  9. * @see #containsBean
  10. */
  11. boolean containsBeanDefinition(String beanName);
  12.  
  13. /**
  14. * Return the number of beans defined in the factory.
  15. * <p>Does not consider any hierarchy this factory may participate in,
  16. * and ignores any singleton beans that have been registered by
  17. * other means than bean definitions.
  18. * @return the number of beans defined in the factory
  19. */
  20. int getBeanDefinitionCount();
  21.  
  22. /**
  23. * Return the names of all beans defined in this factory.
  24. * <p>Does not consider any hierarchy this factory may participate in,
  25. * and ignores any singleton beans that have been registered by
  26. * other means than bean definitions.
  27. * @return the names of all beans defined in this factory,
  28. * or an empty array if none defined
  29. */
  30. String[] getBeanDefinitionNames();
  31.  
  32. /**
  33. * Return the names of beans matching the given type (including subclasses),
  34. * judging from either bean definitions or the value of {@code getObjectType}
  35. * in the case of FactoryBeans.
  36. * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
  37. * check nested beans which might match the specified type as well.
  38. * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
  39. * will get initialized. If the object created by the FactoryBean doesn't match,
  40. * the raw FactoryBean itself will be matched against the type.
  41. * <p>Does not consider any hierarchy this factory may participate in.
  42. * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
  43. * to include beans in ancestor factories too.
  44. * <p>Note: Does <i>not</i> ignore singleton beans that have been registered
  45. * by other means than bean definitions.
  46. * <p>This version of {@code getBeanNamesForType} matches all kinds of beans,
  47. * be it singletons, prototypes, or FactoryBeans. In most implementations, the
  48. * result will be the same as for {@code getBeanNamesForType(type, true, true)}.
  49. * <p>Bean names returned by this method should always return bean names <i>in the
  50. * order of definition</i> in the backend configuration, as far as possible.
  51. * @param type the class or interface to match, or {@code null} for all bean names
  52. * @return the names of beans (or objects created by FactoryBeans) matching
  53. * the given object type (including subclasses), or an empty array if none
  54. * @since 4.2
  55. * @see FactoryBean#getObjectType
  56. * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, ResolvableType)
  57. */
  58. String[] getBeanNamesForType(ResolvableType type);
  59.  
  60. /**
  61. * Return the names of beans matching the given type (including subclasses),
  62. * judging from either bean definitions or the value of {@code getObjectType}
  63. * in the case of FactoryBeans.
  64. * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
  65. * check nested beans which might match the specified type as well.
  66. * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
  67. * will get initialized. If the object created by the FactoryBean doesn't match,
  68. * the raw FactoryBean itself will be matched against the type.
  69. * <p>Does not consider any hierarchy this factory may participate in.
  70. * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
  71. * to include beans in ancestor factories too.
  72. * <p>Note: Does <i>not</i> ignore singleton beans that have been registered
  73. * by other means than bean definitions.
  74. * <p>This version of {@code getBeanNamesForType} matches all kinds of beans,
  75. * be it singletons, prototypes, or FactoryBeans. In most implementations, the
  76. * result will be the same as for {@code getBeanNamesForType(type, true, true)}.
  77. * <p>Bean names returned by this method should always return bean names <i>in the
  78. * order of definition</i> in the backend configuration, as far as possible.
  79. * @param type the class or interface to match, or {@code null} for all bean names
  80. * @return the names of beans (or objects created by FactoryBeans) matching
  81. * the given object type (including subclasses), or an empty array if none
  82. * @see FactoryBean#getObjectType
  83. * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class)
  84. */
  85. String[] getBeanNamesForType(Class<?> type);
  86.  
  87. /**
  88. * Return the names of beans matching the given type (including subclasses),
  89. * judging from either bean definitions or the value of {@code getObjectType}
  90. * in the case of FactoryBeans.
  91. * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
  92. * check nested beans which might match the specified type as well.
  93. * <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set,
  94. * which means that FactoryBeans will get initialized. If the object created by the
  95. * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the
  96. * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
  97. * (which doesn't require initialization of each FactoryBean).
  98. * <p>Does not consider any hierarchy this factory may participate in.
  99. * Use BeanFactoryUtils' {@code beanNamesForTypeIncludingAncestors}
  100. * to include beans in ancestor factories too.
  101. * <p>Note: Does <i>not</i> ignore singleton beans that have been registered
  102. * by other means than bean definitions.
  103. * <p>Bean names returned by this method should always return bean names <i>in the
  104. * order of definition</i> in the backend configuration, as far as possible.
  105. * @param type the class or interface to match, or {@code null} for all bean names
  106. * @param includeNonSingletons whether to include prototype or scoped beans too
  107. * or just singletons (also applies to FactoryBeans)
  108. * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
  109. * <i>objects created by FactoryBeans</i> (or by factory methods with a
  110. * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
  111. * eagerly initialized to determine their type: So be aware that passing in "true"
  112. * for this flag will initialize FactoryBeans and "factory-bean" references.
  113. * @return the names of beans (or objects created by FactoryBeans) matching
  114. * the given object type (including subclasses), or an empty array if none
  115. * @see FactoryBean#getObjectType
  116. * @see BeanFactoryUtils#beanNamesForTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
  117. */
  118. String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
  119.  
  120. /**
  121. * Return the bean instances that match the given object type (including
  122. * subclasses), judging from either bean definitions or the value of
  123. * {@code getObjectType} in the case of FactoryBeans.
  124. * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
  125. * check nested beans which might match the specified type as well.
  126. * <p>Does consider objects created by FactoryBeans, which means that FactoryBeans
  127. * will get initialized. If the object created by the FactoryBean doesn't match,
  128. * the raw FactoryBean itself will be matched against the type.
  129. * <p>Does not consider any hierarchy this factory may participate in.
  130. * Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors}
  131. * to include beans in ancestor factories too.
  132. * <p>Note: Does <i>not</i> ignore singleton beans that have been registered
  133. * by other means than bean definitions.
  134. * <p>This version of getBeansOfType matches all kinds of beans, be it
  135. * singletons, prototypes, or FactoryBeans. In most implementations, the
  136. * result will be the same as for {@code getBeansOfType(type, true, true)}.
  137. * <p>The Map returned by this method should always return bean names and
  138. * corresponding bean instances <i>in the order of definition</i> in the
  139. * backend configuration, as far as possible.
  140. * @param type the class or interface to match, or {@code null} for all concrete beans
  141. * @return a Map with the matching beans, containing the bean names as
  142. * keys and the corresponding bean instances as values
  143. * @throws BeansException if a bean could not be created
  144. * @since 1.1.2
  145. * @see FactoryBean#getObjectType
  146. * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
  147. */
  148. <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;
  149.  
  150. /**
  151. * Return the bean instances that match the given object type (including
  152. * subclasses), judging from either bean definitions or the value of
  153. * {@code getObjectType} in the case of FactoryBeans.
  154. * <p><b>NOTE: This method introspects top-level beans only.</b> It does <i>not</i>
  155. * check nested beans which might match the specified type as well.
  156. * <p>Does consider objects created by FactoryBeans if the "allowEagerInit" flag is set,
  157. * which means that FactoryBeans will get initialized. If the object created by the
  158. * FactoryBean doesn't match, the raw FactoryBean itself will be matched against the
  159. * type. If "allowEagerInit" is not set, only raw FactoryBeans will be checked
  160. * (which doesn't require initialization of each FactoryBean).
  161. * <p>Does not consider any hierarchy this factory may participate in.
  162. * Use BeanFactoryUtils' {@code beansOfTypeIncludingAncestors}
  163. * to include beans in ancestor factories too.
  164. * <p>Note: Does <i>not</i> ignore singleton beans that have been registered
  165. * by other means than bean definitions.
  166. * <p>The Map returned by this method should always return bean names and
  167. * corresponding bean instances <i>in the order of definition</i> in the
  168. * backend configuration, as far as possible.
  169. * @param type the class or interface to match, or {@code null} for all concrete beans
  170. * @param includeNonSingletons whether to include prototype or scoped beans too
  171. * or just singletons (also applies to FactoryBeans)
  172. * @param allowEagerInit whether to initialize <i>lazy-init singletons</i> and
  173. * <i>objects created by FactoryBeans</i> (or by factory methods with a
  174. * "factory-bean" reference) for the type check. Note that FactoryBeans need to be
  175. * eagerly initialized to determine their type: So be aware that passing in "true"
  176. * for this flag will initialize FactoryBeans and "factory-bean" references.
  177. * @return a Map with the matching beans, containing the bean names as
  178. * keys and the corresponding bean instances as values
  179. * @throws BeansException if a bean could not be created
  180. * @see FactoryBean#getObjectType
  181. * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class, boolean, boolean)
  182. */
  183. <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
  184. throws BeansException;
  185.  
  186. /**
  187. * Find all names of beans whose {@code Class} has the supplied {@link Annotation}
  188. * type, without creating any bean instances yet.
  189. * @param annotationType the type of annotation to look for
  190. * @return the names of all matching beans
  191. * @since 4.0
  192. */
  193. String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);
  194.  
  195. /**
  196. * Find all beans whose {@code Class} has the supplied {@link Annotation} type,
  197. * returning a Map of bean names with corresponding bean instances.
  198. * @param annotationType the type of annotation to look for
  199. * @return a Map with the matching beans, containing the bean names as
  200. * keys and the corresponding bean instances as values
  201. * @throws BeansException if a bean could not be created
  202. * @since 3.0
  203. */
  204. Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;
  205.  
  206. /**
  207. * Find an {@link Annotation} of {@code annotationType} on the specified
  208. * bean, traversing its interfaces and super classes if no annotation can be
  209. * found on the given class itself.
  210. * @param beanName the name of the bean to look for annotations on
  211. * @param annotationType the annotation class to look for
  212. * @return the annotation of the given type if found, or {@code null}
  213. * @throws NoSuchBeanDefinitionException if there is no bean with the given name
  214. * @since 3.0
  215. */
  216. <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
  217. throws NoSuchBeanDefinitionException;
  218.  
  219. }

Spring BeanFactory源码学习的更多相关文章

  1. 框架源码系列十一:事务管理(Spring事务管理的特点、事务概念学习、Spring事务使用学习、Spring事务管理API学习、Spring事务源码学习)

    一.Spring事务管理的特点 Spring框架为事务管理提供一套统一的抽象,带来的好处有:1. 跨不同事务API的统一的编程模型,无论你使用的是jdbc.jta.jpa.hibernate.2. 支 ...

  2. 框架源码系列十:Spring AOP(AOP的核心概念回顾、Spring中AOP的用法、Spring AOP 源码学习)

    一.AOP的核心概念回顾 https://docs.spring.io/spring/docs/5.1.3.RELEASE/spring-framework-reference/core.html#a ...

  3. 框架源码系列六:Spring源码学习之Spring IOC源码学习

    Spring 源码学习过程: 一.搞明白IOC能做什么,是怎么做的  1. 搞明白IOC能做什么? IOC是用为用户创建.管理实例对象的.用户需要实例对象时只需要向IOC容器获取就行了,不用自己去创建 ...

  4. Spring mybatis源码学习指引目录

    前言: 分析了很多方面的mybatis的源码以及与spring结合的源码,但是难免出现错综的现象,为了使源码陶冶更为有序化.清晰化,特作此随笔归纳下分析过的内容.博主也为mybatis官方提供过pul ...

  5. 走进Spring Boot源码学习之路和浅谈入门

    Spring Boot浅聊入门 **本人博客网站 **IT小神 www.itxiaoshen.com Spring Boot官网地址:https://spring.io/projects/spring ...

  6. Spring Boot 源码学习之转载

    这次的学习,主要转载了 波波老师的笔记,后续会自己整理一份 1.Spring-Boot源码分析-源码编译:https://dpb-bobokaoya-sm.blog.csdn.net/article/ ...

  7. Spring源码学习

    Spring源码学习--ClassPathXmlApplicationContext(一) spring源码学习--FileSystemXmlApplicationContext(二) spring源 ...

  8. 【目录】Spring 源码学习

    [目录]Spring 源码学习 jwfy 关注 2018.01.31 19:57* 字数 896 阅读 152评论 0喜欢 9 用来记录自己学习spring源码的一些心得和体会以及相关功能的实现原理, ...

  9. 精尽Spring Boot源码分析 - 序言

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

随机推荐

  1. Linux系统date命令的参数及获取时间戳的方法

    date指令相关用法示例 date 用法: date [OPTION]... [+FORMAT]date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] ...

  2. Mac端SVN工具CornerStone详解

    俗话说:"工欲善其事必先利其器": 对于我们程序员来说,不管你是大神,还是小鱼小虾,进入公司之后,都用过源码管理工具,不然你就不是一个合格的程序员,现在各个公司用于源码管理工具通常 ...

  3. The superclass “javax.servlet.http.HttpServlet" was not found on the Java Build Path错误

    1.异常信息 创建maven web项目时,出现 The superclass "javax.servlet.http.HttpServlet" was not found on ...

  4. Java web的几种异常处理 (转)

    一.在servlet容器中处理异常 以下两种方式: 1. 在web.xml定义异常处理  如果没有在web的应用中作异常处理,那么异常就会抛给Servlet容器,应该说此时Servlet容器是处理异常 ...

  5. net.sz.framework 框架 轻松搭建服务---让你更专注逻辑功能---初探

    前言 在之前的文章中,讲解过 threadmodel,socket tcp ,socket http,log,astart ,scripts: 都是分片讲解,从今天开始,将带大家,一窥 net.sz. ...

  6. Swift开发

    1. 模糊效果 iconImageView.image = UIImage(named: "1.png") //效果类实例 let blurEffect = UIBlurEffec ...

  7. 什么东西那么吸引别人的眼球!! -----------------------------------for循环

    认识for循环结构 在编码过程中,把一些重复执行代码采用循环结构进行描述,可以大大减化编码工作, 使得代码更加简洁.宜都... 1.     为什么要用for? 比如: 老师叫小明统计全班人的编号,小 ...

  8. Oracle的基本学习(二)—基本查询

    一.基本查询语句 (1)查看当前用户 show user;   (2)查看当前用户下的表 select * from tab;   (3)查看员工表的结构 desc emp;   (4)选择全部列 S ...

  9. AngularJS1.X学习笔记14-动画(解读文档)

    最近在看算法分析,那个大O啊,小o啊,分治法啊(目前就看到这里),真是搞死了.这回呢休息一下,学学AngularJS动画,上一篇文章根据自由男人的书简单谈到了动画的话题,发现反响很大(好吧,我说慌了, ...

  10. less学习笔记(一)

    less的写法如下 .content { ul{ list-style: none; } li{ height: 25px; line-height: 25px; padding-left: 15px ...