package org.springframework.beans.factory;import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;/*** The root interface for accessing a Spring bean container.* 用于訪問Spring bean容器的根接口。 * <p>This is the basic client view of a bean container;* further interfaces such as {@link ListableBeanFactory} and* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}* are available for specific purposes.這是bean容器的基本客戶端視圖;其他接口,如ListableBeanFactory和org.springframework.beans.factory.config。ConfigurationBeanFactory可用于特定用途。** <p>This interface is implemented by objects that hold a number of bean definitions,* each uniquely identified by a String name. Depending on the bean definition,* the factory will return either an independent instance of a contained object* (the Prototype design pattern), or a single shared instance (a superior* alternative to the Singleton design pattern, in which the instance is a* singleton in the scope of the factory). Which type of instance will be returned* depends on the bean factory configuration: the API is the same. Since Spring* 2.0, further scopes are available depending on the concrete application* context (e.g. "request" and "session" scopes in a web environment).這個接口是由包含許多bean定義的對象實現的,每個定義都由一個String名稱唯一標識。根據bean定義,工廠將返回包含對象的獨立實例(原型設計模式)或單個共享實例(Singleton設計模式的高級替代方案,其中實例是工廠范圍內的單例)。返回哪種類型的實例取決于bean工廠配置:API是相同的。自Spring 2.0以來,根據具體的應用程序上下文(例如,web環境中的“請求”和“會話”作用域),可以使用更多的作用域。** <p>The point of this approach is that the BeanFactory is a central registry* of application components, and centralizes configuration of application* components (no more do individual objects need to read properties files,* for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and* Development" for a discussion of the benefits of this approach.這種方法的要點是BeanFactory是應用程序組件的中心注冊表,并集中應用程序組件配置(例如,單個對象不再需要讀取屬性文件)。請參閱“專家一對一J2EE設計和開發”的第4章和第11章,以討論這種方法的好處。** <p>Note that it is generally better to rely on Dependency Injection* ("push" configuration) to configure application objects through setters* or constructors, rather than use any form of "pull" configuration like a* BeanFactory lookup. Spring's Dependency Injection functionality is* implemented using this BeanFactory interface and its subinterfaces.請注意,通常最好依靠依賴注入(“推”配置)通過setter或構造函數來配置應用程序對象,而不是使用任何形式的“拉”配置(如BeanFactory查找)。Spring的依賴注入功能是使用這個BeanFactory接口及其子接口實現的。** <p>Normally a BeanFactory will load bean definitions stored in a configuration* source (such as an XML document), and use the {@code org.springframework.beans}* package to configure the beans. However, an implementation could simply return* Java objects it creates as necessary directly in Java code. There are no* constraints on how the definitions could be stored: LDAP, RDBMS, XML,* properties file, etc. Implementations are encouraged to support references* amongst beans (Dependency Injection).通常,BeanFactory將加載存儲在配置源(如XML文檔)中的bean定義,并使用org.springframework.beans包來配置bean。然而,實現可以簡單地返回它在必要時直接在Java代碼中創建的Java對象。定義的存儲方式沒有任何限制:LDAP、RDBMS、XML、屬性文件等。鼓勵實現支持bean之間的引用(依賴注入)。** <p>In contrast to the methods in {@link ListableBeanFactory}, all of the* operations in this interface will also check parent factories if this is a* {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance,* the immediate parent factory will be asked. Beans in this factory instance* are supposed to override beans of the same name in any parent factory.*與ListableBeanFactory中的方法不同,如果這是HierarchicalBeanFactory,則此接口中的所有操作也將檢查父工廠。如果在這個工廠實例中沒有找到bean,則會詢問直接的父工廠。這個工廠實例中的bean應該覆蓋任何父工廠中相同名稱的bean。* <p>Bean factory implementations should support the standard bean lifecycle interfaces* as far as possible. The full set of initialization methods and their standard order is:Bean工廠實現應該盡可能支持標準的Bean生命周期接口。整套初始化方法及其標準順序為:1.BeanNameAware's setBeanName
2.BeanClassLoaderAware's setBeanClassLoader
3.BeanFactoryAware's setBeanFactory
4.EnvironmentAware's setEnvironment
5.EmbeddedValueResolverAware's setEmbeddedValueResolver
6.ResourceLoaderAware's setResourceLoader (僅在應用程序上下文中運行時適用)
7.ApplicationEventPublisherAware's setApplicationEventPublisher (僅在應用程序上下文中運行時適用)
8.MessageSourceAware's setMessageSource (僅在應用程序上下文中運行時適用)
9.ApplicationContextAware's setApplicationContext (僅在應用程序上下文中運行時適用)
10.ServletContextAware's setServletContext (僅適用于在web應用程序上下文中運行時)
11.postProcessBeforeInitialization methods of BeanPostProcessors
12.InitializingBean's afterPropertiesSet
13.a custom init-method definition
14.postProcessAfterInitialization methods of BeanPostProcessors在idea中以下@see可以跳轉到對應的接口和抽象類中* @author Rod Johnson* @author Juergen Hoeller* @author Chris Beams* @since 13 April 2001* @see BeanNameAware#setBeanName* @see BeanClassLoaderAware#setBeanClassLoader* @see BeanFactoryAware#setBeanFactory* @see org.springframework.context.EnvironmentAware#setEnvironment* @see org.springframework.context.EmbeddedValueResolverAware#setEmbeddedValueResolver* @see org.springframework.context.ResourceLoaderAware#setResourceLoader* @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher* @see org.springframework.context.MessageSourceAware#setMessageSource* @see org.springframework.context.ApplicationContextAware#setApplicationContext* @see org.springframework.web.context.ServletContextAware#setServletContext* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization* @see InitializingBean#afterPropertiesSet* @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor#postProcessBeforeDestruction* @see DisposableBean#destroy* @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName*/
public interface BeanFactory {/*** Used to dereference a {@link FactoryBean} instance and distinguish it from* beans <i>created</i> by the FactoryBean. For example, if the bean named* {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}* will return the factory, not the instance returned by the factory.*/
用于取消引用FactoryBean實例,并將其與FactoryBean創建的bean區分開來。例如,如果名為myJndiObject的bean是FactoryBean,那么獲取&myJndiObject將返回工廠,而不是工廠返回的實例。String FACTORY_BEAN_PREFIX = "&";/*** 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*/返回指定bean的一個實例,該實例可以是共享的,也可以是獨立的。
此方法允許使用Spring BeanFactory作為Singleton或Prototype設計模式的替代品。在Singleton bean的情況下,調用者可以保留對返回對象的引用。Object getBean(String name) throws BeansException;/*** 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*/返回指定bean的一個實例,該實例可以是共享的,也可以是獨立的。
行為與getBean(String)相同,但如果bean不是必需的類型,則通過拋出BeanNotOfRequiredTypeException來提供類型安全性度量。這意味著ClassCastException不能像getBean(String)那樣在正確地轉換結果時拋出。<T> T getBean(String name, Class<T> requiredType) throws BeansException;/*** 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*/返回指定bean的一個實例,該實例可以是共享的,也可以是獨立的。
允許指定顯式構造函數參數/工廠方法參數,覆蓋bean定義中指定的默認參數(如果有的話)。Object getBean(String name, Object... args) throws BeansException;/*** 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*/返回唯一匹配給定對象類型的bean實例(如果有的話)。
此方法進入ListableBeanFactory按類型查找區域,但也可以根據給定類型的名稱轉換為傳統的按名稱查找。對于跨bean集的更廣泛的檢索操作,請使用ListableBeanFactory和/或BeanFactoryUtils。<T> T getBean(Class<T> requiredType) throws BeansException;/*** 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*/返回指定bean的一個實例,該實例可以是共享的,也可以是獨立的。
允許指定顯式構造函數參數/工廠方法參數,覆蓋bean定義中指定的默認參數(如果有的話)。
此方法進入ListableBeanFactory按類型查找區域,但也可以根據給定類型的名稱轉換為傳統的按名稱查找。對于跨bean集的更廣泛的檢索操作,請使用ListableBeanFactory和/或BeanFactoryUtils。<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;/*** 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)*/返回指定bean的提供程序,允許延遲按需檢索實例,包括可用性和唯一性選項。
要匹配泛型類型,請考慮getBeanProvider(可解析類型)。<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);/*** 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()*/返回指定bean的提供程序,允許延遲按需檢索實例,包括可用性和唯一性選項。此變體允許指定要匹配的泛型類型,類似于方法/構造函數參數中具有泛型類型聲明的反射注入點。
請注意,與反射注入點相比,這里不支持bean的集合。要以編程方式檢索與特定類型匹配的bean列表,請在此處指定實際bean類型作為參數,然后使用ObjectProvider.orderedStream()或其惰性流/迭代選項。
此外,根據Java賦值規則,泛型匹配在這里是嚴格的。對于具有未檢查語義的寬松回退匹配(類似于“未檢查”Java編譯器警告),如果此變體沒有完全的通用匹配,請考慮使用原始類型調用getBeanProvider(Class)作為第二步。<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);/*** 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*/這個bean工廠是否包含給定名稱的bean定義或外部注冊的singleton實例?
如果給定的名稱是一個別名,它將被翻譯回相應的規范bean名稱。
如果這個工廠是分層的,將詢問任何父工廠是否在這個工廠實例中找不到bean。
如果找到與給定名稱匹配的bean定義或singleton實例,則無論命名的bean定義是具體的還是抽象的、懶惰的還是渴望的、在范圍內的還是不在,此方法都將返回true。因此,請注意,此方法的真實返回值并不一定表示getBean能夠獲得相同名稱的實例。boolean containsBean(String name);/*** 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*/這個bean是共享的singleton嗎?也就是說,getBean是否總是返回相同的實例?
注意:這種返回false的方法并不能清楚地指示獨立的實例。它指示非單例實例,這些實例也可能對應于作用域bean。使用isPrototype操作顯式檢查獨立實例。
將別名翻譯回相應的規范bean名稱。
將詢問父工廠是否在此工廠實例中找不到bean。boolean isSingleton(String name) throws NoSuchBeanDefinitionException;/*** 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*/這個Bean是原型嗎?也就是說,getBean總是會返回獨立的實例嗎?
注意:這個返回false的方法并不能清楚地指示一個singleton對象。它指示非獨立實例,這些實例也可能對應于作用域bean。使用isSingleton操作顯式檢查共享的單例實例boolean isPrototype(String name) throws NoSuchBeanDefinitionException;/*** 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*/檢查具有給定名稱的bean是否與指定的類型匹配。更具體地說,檢查給定名稱的getBean調用是否會返回可分配給指定目標類型的對象。boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;/*** 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*/檢查具有給定名稱的bean是否與指定的類型匹配。更具體地說,檢查給定名稱的getBean調用是否會返回可分配給指定目標類型的對象。boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;/*** 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*/確定具有給定名稱的bean的類型。更具體地說,確定getBean將為給定名稱返回的對象類型。
對于FactoryBean,返回FactoryBean創建的對象類型,如FactoryBean.getObjectType()所示。這可能會導致初始化先前未初始化的FactoryBean(請參閱getType(String,boolean))。@NullableClass<?> getType(String name) throws NoSuchBeanDefinitionException;/*** 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*/確定具有給定名稱的bean的類型。更具體地說,確定getBean將為給定名稱返回的對象類型。
對于FactoryBean,返回FactoryBean創建的對象類型,如FactoryBean.getObjectType()所示。根據allowFactoryBaininit標志,如果沒有可用的早期類型信息,這可能會導致初始化先前未初始化的FactoryBean。@NullableClass<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;/*** 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*/返回給定bean名稱的別名(如果有的話)。
當在getBean調用中使用時,所有這些別名都指向同一個bean。
如果給定的名稱是一個別名,那么將返回相應的原始bean名稱和其他別名(如果有的話),原始bean名稱是數組中的第一個元素。String[] getAliases(String name);}
總結下來為這幾個屬性和方法。
如果名為myJndiObject的bean是FactoryBean,那么獲取&myJndiObject將返回工廠,而不是工廠返回的實例
String FACTORY_BEAN_PREFIX = "&";
通過一些參數尋找獲取bean
Object getBean(String name) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
?通過一些參數尋找獲取bean的Provider
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
?判斷name這個bean是不是這個工廠生產的
boolean containsBean(String name);
?判斷這個bean是單例模式還是原型模式。單例就是這個對象全局只有一個。原型就是這個Bean每次被使用都會生成一個新的對象。
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
??判斷這個bean是否某類型的bean
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
?獲取這個bean的類型
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
獲取這個bean的別名
String[] getAliases(String name);
先閱讀源碼,再看下面這個總結,可以知道beanFactory這個接口定義的就是對bean的一些基本操作,查詢bean,獲取bean,判斷bean的存在,bean的類型等操作。