BeanFactory 是 Spring 框架中的一个核心接口,它定义了访问 Spring 容器中 Bean 的基本操作,它是实现 IoC 和 DI 的基础。BeanFactory 负责管理应用程序中的对象(即 Bean),并提供了访问这些对象的方法。
除了 BeanFactory 接口,Spring 还提供了许多其他的 BeanFactory 子接口,如 ConfigurableBeanFactory、ListableBeanFactory、HierarchicalBeanFactory 等,以及 ApplicationContext 接口。这些接口都是在 BeanFactory 接口的基础上扩展而来,提供了更加丰富的功能,如 Bean 生命周期管理、Bean 自动装配、事件机制等。
- BeanFactory
public interface BeanFactory {}
-
getBean(String name)
:根据bean的名称获取该bean的实例。如果该bean是singleton作用域的,那么返回的是同一个实例;如果是prototype作用域的,那么每次调用都会返回一个新的实例。如果找不到该名称对应的bean,则抛出NoSuchBeanDefinitionException
异常。
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>This method allows a Spring BeanFactory to be used as a replacement for the
* Singleton or Prototype design pattern. Callers may retain references to
* returned objects in the case of Singleton beans.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no bean with the specified name
* @throws BeansException if the bean could not be obtained
*/
Object getBean(String name) throws BeansException;
-
getBean(String name, Class<T> requiredType)
:根据bean的名称和类型获取该bean的实例。如果该bean是singleton作用域的,那么返回的是同一个实例;如果是prototype作用域的,那么每次调用都会返回一个新的实例。如果找不到该名称对应的bean或者该bean的类型与指定的类型不匹配,则抛出NoSuchBeanDefinitionException
或者BeanNotOfRequiredTypeException
异常。
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
* safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
* required type. This means that ClassCastException can't be thrown on casting
* the result correctly, as can happen with {@link #getBean(String)}.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
* @throws BeansException if the bean could not be created
*/
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
-
getBean(String name, Object... args)
:根据bean的名称和指定的构造函数参数获取该bean的实例。如果该bean是singleton作用域的,那么返回的是同一个实例;如果是prototype作用域的,那么每次调用都会返回一个新的实例。如果找不到该名称对应的bean或者该bean不是prototype作用域,则抛出NoSuchBeanDefinitionException
或者BeanDefinitionStoreException
异常。
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
Object getBean(String name, Object... args) throws BeansException;
-
getBean(Class<T> requiredType)
:根据bean的类型获取该bean的实例。如果有且仅有一个符合类型的bean,则返回该bean的实例。
/**
* Return the bean instance that uniquely matches the given object type, if any.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the single bean matching the required type
* @throws NoSuchBeanDefinitionException if no bean of the given type was found
* @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
* @throws BeansException if the bean could not be created
* @since 3.0
* @see ListableBeanFactory
*/
<T> T getBean(Class<T> requiredType) throws BeansException;
-
getBean(Class<T> requiredType, Object... args)
:根据bean的类型和指定的构造函数参数获取该bean的实例。如果有且仅有一个符合类型的bean,则返回该bean的实例;如果找不到该类型对应的bean或者有多个符合类型的bean,则抛出NoSuchBeanDefinitionException
或者BeanDefinitionStoreException
异常。
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
* but may also be translated into a conventional by-name lookup based on the name
* of the given type. For more extensive retrieval operations across sets of beans,
* use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
* @param requiredType type the bean must match; can be an interface or superclass
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 4.1
*/
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
-
getBeanProvider(Class<T> requiredType)
:它返回一个指定 Bean 的提供者。提供者可以用于延迟加载 Bean 实例,包括可用性和唯一性选项。 -
ObjectProvider 接口是 Spring 5 新增的功能之一,它允许开发者以一种更加灵活的方式获取 Bean 实例。与传统的 getBean() 方法不同,ObjectProvider 接口支持延迟加载、按需获取、按名称获取、按类型获取等多种方式获取 Bean 实例。
/**
* Return a provider for the specified bean, allowing for lazy on-demand retrieval
* of instances, including availability and uniqueness options.
* <p>For matching a generic type, consider {@link #getBeanProvider(ResolvableType)}.
* @param requiredType type the bean must match; can be an interface or superclass
* @return a corresponding provider handle
* @since 5.1
* @see #getBeanProvider(ResolvableType)
*/
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
-
getBeanProvider(ResolvableType requiredType)
:返回一个指定 Bean 的提供者,允许进行延迟的按需检索实例,包括可用性和唯一性选项。该方法允许开发者指定一个泛型类型来获取 Bean 实例,类似于反射注入点中方法/构造函数参数中的泛型类型声明。
/**
* Return a provider for the specified bean, allowing for lazy on-demand retrieval
* of instances, including availability and uniqueness options. This variant allows
* for specifying a generic type to match, similar to reflective injection points
* with generic type declarations in method/constructor parameters.
* <p>Note that collections of beans are not supported here, in contrast to reflective
* injection points. For programmatically retrieving a list of beans matching a
* specific type, specify the actual bean type as an argument here and subsequently
* use {@link ObjectProvider#orderedStream()} or its lazy streaming/iteration options.
* <p>Also, generics matching is strict here, as per the Java assignment rules.
* For lenient fallback matching with unchecked semantics (similar to the ´unchecked´
* Java compiler warning), consider calling {@link #getBeanProvider(Class)} with the
* raw type as a second step if no full generic match is
* {@link ObjectProvider#getIfAvailable() available} with this variant.
* @return a corresponding provider handle
* @param requiredType type the bean must match; can be a generic type declaration
* @since 5.1
* @see ObjectProvider#iterator()
* @see ObjectProvider#stream()
* @see ObjectProvider#orderedStream()
*/
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
-
containsBean(String name)
:判断是否存在指定名称的bean。该方法用于判断 Bean 工厂中是否包含指定名称的 Bean 定义或外部注册的单例实例。如果给定的名称是一个别名,则该方法会将其转换回相应的规范化 Bean 名称。 - 如果 Bean 工厂是分层的,且在当前工厂实例中找不到指定名称的 Bean,该方法会向任何父工厂发出查询请求。
- 如果找到与给定名称匹配的 Bean 定义或单例实例,则该方法将返回 true,无论该命名 Bean 定义是具体的还是抽象的、惰性的还是急切的、在范围内还是不在范围内。因此,请注意,从此方法返回 true 并不一定表示 {@link #getBean} 将能够为同一名称获取实例。
/**
* Does this bean factory contain a bean definition or externally registered singleton
* instance with the given name?
* <p>If the given name is an alias, it will be translated back to the corresponding
* canonical bean name.
* <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
* be found in this factory instance.
* <p>If a bean definition or singleton instance matching the given name is found,
* this method will return {@code true} whether the named bean definition is concrete
* or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
* return value from this method does not necessarily indicate that {@link #getBean}
* will be able to obtain an instance for the same name.
* @param name the name of the bean to query
* @return whether a bean with the given name is present
*/
boolean containsBean(String name);
-
isSingleton(String name)
:判断指定名称的bean是否是singleton作用域的。该方法用于判断指定名称的 Bean 是否为共享的单例,也就是 {@link #getBean} 方法是否总是返回同一个实例。 -
需要注意的是,该方法返回 false 并不一定表示独立的实例。它只表示非单例实例,这可能对应于作用域 Bean。如果要明确检查独立实例,请使用 {@link #isPrototype} 操作。
-
该方法会将别名转换回相应的规范化 Bean 名称,并在当前工厂实例中查找指定名称的 Bean。如果找到了 Bean,则返回一个 boolean 类型的值,表示该 Bean 是否为单例。如果未找到 Bean,则会向任何父工厂发出查询请求。如果在任何工厂中都找不到 Bean,则抛出 NoSuchBeanDefinitionException 异常。
/**
* Is this bean a shared singleton? That is, will {@link #getBean} always
* return the same instance?
* <p>Note: This method returning {@code false} does not clearly indicate
* independent instances. It indicates non-singleton instances, which may correspond
* to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly
* check for independent instances.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean corresponds to a singleton instance
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @see #getBean
* @see #isPrototype
*/
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
-
isPrototype(String name)
:判断指定名称的bean是否是prototype作用域的。该方法用于判断指定名称的 Bean 是否为原型,也就是 {@link #getBean} 方法是否总是返回独立的实例。 -
需要注意的是,该方法返回 false 并不一定表示单例对象。它只表示非独立的实例,这可能对应于作用域 Bean。如果要明确检查共享单例实例,请使用 {@link #isSingleton} 操作。
/**
* Is this bean a prototype? That is, will {@link #getBean} always return
* independent instances?
* <p>Note: This method returning {@code false} does not clearly indicate
* a singleton object. It indicates non-independent instances, which may correspond
* to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly
* check for a shared singleton instance.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return whether this bean will always deliver independent instances
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.3
* @see #getBean
* @see #isSingleton
*/
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
-
isTypeMatch(String name, ResolvableType typeToMatch)
:判断指定名称的bean是否与指定类型匹配。
/**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code ResolvableType})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 4.2
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
-
isTypeMatch(String name, Class<?> typeToMatch)
:判断指定名称的bean是否与指定类型匹配。
**
* Check whether the bean with the given name matches the specified type.
* More specifically, check whether a {@link #getBean} call for the given name
* would return an object that is assignable to the specified target type.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a {@code Class})
* @return {@code true} if the bean type matches,
* {@code false} if it doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 2.0.1
* @see #getBean
* @see #getType
*/
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
-
Class<?> getType(String name):该方法用于确定给定名称的 Bean 的类型。更具体地说,它确定了调用 {@link #getBean} 方法返回的对象的类型。
/**
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}. This may lead to the initialization
* of a previously uninitialized {@code FactoryBean} (see {@link #getType(String, boolean)}).
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 1.1.2
* @see #getBean
* @see #isTypeMatch
*/
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
-
Class<?> getType(String name, boolean allowFactoryBeanInit):该方法用于确定给定名称的 Bean 的类型。更具体地说,它确定了调用 {@link #getBean} 方法返回的对象的类型。
- 对于 FactoryBean,返回 FactoryBean 创建的对象类型,由 {@link FactoryBean#getObjectType()} 公开。根据 {@code allowFactoryBeanInit} 标志的不同,这可能会导致先前未初始化的 FactoryBean 的初始化。当 allowFactoryBeanInit 为 true 时,Spring 容器会尝试初始化 FactoryBean,以确定其实际类型。
/**
* Determine the type of the bean with the given name. More specifically,
* determine the type of object that {@link #getBean} would return for the given name.
* <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
* as exposed by {@link FactoryBean#getObjectType()}. Depending on the
* {@code allowFactoryBeanInit} flag, this may lead to the initialization of a previously
* uninitialized {@code FactoryBean} if no early type information is available.
* <p>Translates aliases back to the corresponding canonical bean name.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the name of the bean to query
* @param allowFactoryBeanInit whether a {@code FactoryBean} may get initialized
* just for the purpose of determining its object type
* @return the type of the bean, or {@code null} if not determinable
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 5.2
* @see #getBean
* @see #isTypeMatch
*/
@Nullable
Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
-
String[] getAliases(String name):该方法用于获取给定 Bean 名称的所有别名。这些别名在调用 {@link #getBean} 方法时都指向同一个 Bean。
- 如果给定的名称是别名,则返回相应的原始 Bean 名称和其他别名(如果有),其中原始 Bean 名称是数组中的第一个元素。
- 该方法会将别名转换回相应的规范化 Bean 名称,并在当前工厂实例中查找指定名称的 Bean。如果找到了 Bean,则返回一个 String 数组,表示该 Bean 的所有别名。如果未找到 Bean,则会向任何父工厂发出查询请求。如果在任何工厂中都找不到 Bean,则返回一个空数组。
/**
* Return the aliases for the given bean name, if any.
* <p>All of those aliases point to the same bean when used in a {@link #getBean} call.
* <p>If the given name is an alias, the corresponding original bean name
* and other aliases (if any) will be returned, with the original bean name
* being the first element in the array.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the bean name to check for aliases
* @return the aliases, or an empty array if none
* @see #getBean
*/
String[] getAliases(String name);