Spring容器架构
Spring容器家族
BeanFactory:Spring容器的基石,顶级容器接口
在Spring官方文档中,称org.springframework.context.ApplicationContext
这个接口就代表了Spring的容器,在解释ApplicationContext
之前,必须要先介绍Spring容器的基石,BeanFactory
接口。ApplicationContext
就是继承了BeanFactory
接口的一种高级容器接口。而BeanFactory
是简单容器的代表,是Spring容器家族的基石,所有的容器都必须实现这个接口。
BeanFactory接口的源码,主要规定了一些容器的基本功能,其中有7个获取Bean或者Bean提供者的方法,5个判断型的方法,2个获取类型的方法,1个获取别名的方法。通过这些方法,可以看出BeanFactory是一个典型的工厂模式的工厂接口。
public interface BeanFactory { /** * 对FactoryBean的转移定义,提供获取FactoryBean实例的方法。 * 如果定义bean时是通过工厂模式配置Bean的,那么通过bean的名字检索FactoryBean时 * 得到的会是FactoryBean生产出来的实例,如果想得到工厂本身,需要进行转义 */ String FACTORY_BEAN_PREFIX = "&"; /** * 不同的获取Bean的方法 */ Object getBean(String var1) throws BeansException; <T> T getBean(String var1, Class<T> var2) throws BeansException; Object getBean(String var1, Object... var2) throws BeansException; <T> T getBean(Class<T> var1) throws BeansException; <T> T getBean(Class<T> var1, Object... var2) throws BeansException; /** * 获取Bean的提供者(工厂) */ <T> ObjectProvider<T> getBeanProvider(Class<T> var1); <T> ObjectProvider<T> getBeanProvider(ResolvableType var1); // 检索是否包含指定名字的bean boolean containsBean(String name); // 判断指定名字的bean是否为单例 boolean isSingleton(String name) throws NoSuchBeanDefinitionException; // 判断指定名字的bean是否为原型 boolean isPrototype(String name) throws NoSuchBeanDefinitionException; /** * 指定名字的Bean是否匹配指定的类型 */ boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException; /** * 获取指定名字的Bean的类型 */ @Nullable Class<?> getType(String name) throws NoSuchBeanDefinitionException; @Nullable Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException; // 获取指定名字Bean的所有别名 String[] getAliases(String name); }
顶级二级接口:ListableBeanFactory和HierarchicalBeanFactroy。
ListableBeanFactory:该接口拥有列出工厂中所有Bean的能力。ListableBeanFactory主要对外提供了批量获取Bean和BeanDefinition的方法,拓展类了BeanFactory的功能,是一个非常重要的接口。
public interface ListableBeanFactory extends BeanFactory { // 检索是否包含给定beanName的BeanDefinition boolean containsBeanDefinition(String beanName); // 获取工厂中BeanDefinition的数量 int getBeanDefinitionCount(); // 获取工厂中所有BeanDefinition的Names String[] getBeanDefinitionNames(); // 获取指定类型的beanNames String[] getBeanNamesForType(ResolvableType type); String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit); String[] getBeanNamesForType(@Nullable Class<?> type); String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit); // 根据指定的类型来获取所有Bean <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException; <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException; // 根据指定的直接获取beanNames String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType); // 获取所有指定注解标注的Bean实例,Autowired就是使用的该接口 Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException; // 查找指定Bean中含有的注解类型 @Nullable <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException; }
HierarchicalBeanFactroy接口:顾名思义,这是一个分层的工厂。该接口实现了Bean工厂的分层。提供了一个非常重要的功能——工厂分层,通过工厂分层,SpringIoC容器可以建立父子层级关联的容器体系,子容器可以访问父容器中的Bean,而父容器不能访问子容器中的Bean。在容器内,Bean的id必须是唯一的,但子容器可以拥有一个和父容器id相同的Bean。父子容器层级体系增强了Spring容器架构的扩展性和灵活性,因为第三方可以通过编程的方式,为一个已经存在的容器添加一个或多个特殊用途的子容器,以提供一些额外的功能,Spring使用父子容器实现了很多功能,比如在Spring MVC中,展现层Bean位于一个子容器中,而业务层和持久层的Bean位于父容器中。这样,展现层Bean就可以引用业务层和持久层的Bean,而业务层和持久层的Bean则看不到展现层的Bean。
public interface HierarchicalBeanFactory extends BeanFactory { /** * 返回父级工厂 */ @Nullable BeanFactory getParentBeanFactory(); /** * 检索本地工厂是否包含指定名字的Bean */ boolean containsLocalBean(String name); }
复杂配置的Bean工厂:ConfigurableBeanFactory接口
ConfigurableBeanFactory接口是一个继承了HierarchicalBeanFactroy的子接口,同时该接口还继承了SingletonBeanRegistry接口,SingletonBeanRegistry是一个用来注册单例类的接口,提供了同意访问单例Bean的功能,ConfigurableBeanFactory接口主要扩展了一些复杂的对单例Bean的配置与操作,虽然这个接口并没有被ApplicationContext高级容器体系所继承,但是一般的容器实现类都会继承或实现这个接口,目的是使用一种统一的方式对外暴露管理单例Bean的方式。SingletonBeanRegistry接口的方法如下图:
public interface SingletonBeanRegistry { /** * 单例的注册,如果脱离生命周期单独调用该方法,就是单纯的注册而不执行 * 诸如生命周期回调等相关 * 通常,是容器在基于 BeanDefinition 创建 singleton 时调用该方法的 */ void registerSingleton(String beanName, Object singletonObject); /** * 获取以及实例化完成的 singleton * 1)手动 registerSingleton 注册的 * 2)容器基于 BeanDefinition 实例化完成后注册的 */ @Nullable Object getSingleton(String beanName); /** * 检查指定 singleton 是否存在 * 该方法 + ListableBeanFactory#containsBeanDefinition:可以查看当前容器中是否可以 * 获取到指定 name 的 bean,无论它是否实例化完成 * BeanFactory#containsBean 在上一步基础上,还可以查找父级容器 */ boolean containsSingleton(String beanName); // 上述 singleton 名称数组 String[] getSingletonNames(); // 上述 singleton 个数 int getSingletonCount(); // 单例锁对象 Object getSingletonMutex(); }
ConfigurableBeanFactory接口的方法:
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry { //单例 String SCOPE_SINGLETON = "singleton"; //原型 String SCOPE_PROTOTYPE = "prototype"; //设置父类的BeanFactory,可以在HierarchicalBeanFactory中看到父类的BeanFactory的设置 void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException; //设置类加载器 void setBeanClassLoader(ClassLoader beanClassLoader); //获取类加载器 ClassLoader getBeanClassLoader(); //设置临时加载器 void setTempClassLoader(ClassLoader tempClassLoader); //获取临时加载器 ClassLoader getTempClassLoader(); //设置是否缓存源,false,从新从类加载器加载 void setCacheBeanMetadata(boolean cacheBeanMetadata); //是否缓存了definitions boolean isCacheBeanMetadata(); //bean的表达式解析 void setBeanExpressionResolver(BeanExpressionResolver resolver); //获取bean的表达式解析 BeanExpressionResolver getBeanExpressionResolver(); //设置一个转换服务 void setConversionService(ConversionService conversionService); //获取一个转换服务 ConversionService getConversionService(); //设置属性注册员 void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); //注册属性编辑器 void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass); //复杂属性编辑器 void copyRegisteredEditorsTo(PropertyEditorRegistry registry); //设置类型转换器 void setTypeConverter(TypeConverter typeConverter); //获取类型转换器 TypeConverter getTypeConverter(); // 增加一个嵌入式的StringValueResolve void addEmbeddedValueResolver(StringValueResolver valueResolver); //确定定是否有一个嵌入式的value resolver已经在这个bean factory中注册了,并且可以通过resolveEmbeddedValue函数来应用. String resolveEmbeddedValue(String value); //增加一个BeanPostProcessor的处理器 前后 void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); //获取BeanPostProcessor的数量 int getBeanPostProcessorCount(); //注册bean的范围 void registerScope(String scopeName, Scope scope); //获取bean的范围 String[] getRegisteredScopeNames(); //获取注册的范围 Scope getRegisteredScope(String scopeName); //返回本工厂的一个安全访问上下文 AccessControlContext getAccessControlContext(); //复制其他工程的属性配置 void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); //给指定的bean注册别名 void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; //根据StringValueResolver来移除bean void resolveAliases(StringValueResolver valueResolver); //返回合并后的Beandefinition BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; //判断bean是否是FactoryBean boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; //设置一个是否正在创建的bean void setCurrentlyInCreation(String beanName, boolean inCreation); //判断bean是否正在创建 boolean isCurrentlyInCreation(String beanName); //为bean注册一个依赖bean void registerDependentBean(String beanName, String dependentBeanName); //获取bean的所有依赖bean String[] getDependentBeans(String beanName); //返回给定名字Bean所依赖的所有Bean名称. String[] getDependenciesForBean(String beanName); //销毁指定的bean void destroyBean(String beanName, Object beanInstance); //销毁指定的 void destroyScopedBean(String beanName); //销毁单例对象 void destroySingletons(); }
自动装配工厂:AutowireCapableBeanFactory接口
直接继承自BeanFactory接口,主要作用是将自动装配的能力对外暴露出来,可以通过实现此接口实现自动装配能力,但是正常情况下不应该使用该接口。此接口主要针对框架之外,没有向Spring托管的Bean的应用。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 */ //表明没有外部定义自动装配的bean int AUTOWIRE_NO = 0; //根据名称自动装配bean(适用于Bean所有属性的setter) int AUTOWIRE_BY_NAME = 1; //根据类型自动装配bean(适用于Bean所有属性的setter) int AUTOWIRE_BY_TYPE = 2; //根据构造器自动装配bean(构造函数) int AUTOWIRE_CONSTRUCTOR = 3; //通过class的内部来自动装配bean //已经被启用 @Deprecated int AUTOWIRE_AUTODETECT = 4; //------------------------------------------------------------------------- // Typical methods for creating and populating external bean instances //------------------------------------------------------------------------- //根据给定的class创建bean <T> T createBean(Class<T> beanClass) throws BeansException; //通过调用给定Bean的after-instantiation及post-processing接口,对bean进行配置。 void autowireBean(Object existingBean) throws BeansException; // 配置参数中指定的bean,包括自动装配其域,对其应用如setBeanName功能的回调函数。 Object configureBean(Object existingBean, String beanName) throws BeansException; //解析出在Factory中与指定Bean有指定依赖关系的Bean Object resolveDependency(DependencyDescriptor descriptor, String beanName) throws BeansException; // 创建一个指定class的实例,通过参数可以指定其自动装配模式(by-name or by-type). Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; //通过指定的自动装配策略来初始化一个Bean。 Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException; // 通过指定的自动装配方式来对给定的Bean进行自动装配 void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException; //将参数中指定了那么的Bean,注入给定实例当中 void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException; //初始化参数中指定的Bean,调用任何其注册的回调函数如setBeanName、setBeanFactory等。 Object initializeBean(Object existingBean, String beanName) throws BeansException; //调用参数中指定Bean的postProcessBeforeInitialization方法 Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException; // 调用参数中指定Bean的postProcessAfterInitialization方法 Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException; //销毁参数中指定的Bean void destroyBean(Object existingBean); //解析指定Bean在Factory中的依赖关系 Object resolveDependency(DependencyDescriptor descriptor, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException; }
- Bean工厂接口的集大成者:ConfigurableListableBeanFactory 接口
继承了ListableBeanFactory
和可配置bean工厂ConfigurableBeanFactory
接口的子接口,同时它还继承了AutowireCapableBeanFactory
接口,并且自身还扩展了一些功能 可配置bean工厂
ConfigurableBeanFactory
接口,有两个父接口,一个为HierarchicalBeanFactory,一个为SingletonBeanRegistryConfigurableBeanFactory接口源码ConfigurableBeanFactory接口主要提供了,bean作用域,类加载器,临时类加载器,Spring EL解决器,转换服务 ConversionService,属性编辑器注册器,嵌入值解决器,bean后处理的配置操作,同时提供了,是否缓存bean的元数据,设置bean的创建状态,判断bean是否为工厂bean,拷贝bean工厂的配置,获取bean的定义,设置bean的别名,解决基于bean的name的依赖,获取bean的依赖bean信息和获取依赖于bean的bean的name操作,还有销毁给定作用域的bean。需要注意的是,设置bean的创建状态操作属于容器的内部操作,获取作用域时,不包括单例和原型作用域。此接口不能够在应用中直接调用,要配合{@link org.springframework.beans.factory.BeanFactory} 或@link org.springframework.beans.factory.ListableBeanFactory}使用。此接口的扩展接口,运行框架内部使用,用于访问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; /** *ConfigurableBeanFactory是一个大多数bean工厂都会实现的接口。为配置bean工厂和工厂接口中客户端操作, *提供了便利。 * 配置bean工厂不以为者可以在应用代码中,直接使用:应配合{@link org.springframework.beans.factory.BeanFactory} * 或@link org.springframework.beans.factory.ListableBeanFactory}使用。 * 此接口的扩展接口,运行框架内部使用,用于访问bean工厂的配置方法。 * * @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 { /** * 标准的单例作用域模式标识。一般的作用域可以通过{@code registerScope}方法注册。 * @see #registerScope */ String SCOPE_SINGLETON = "singleton"; /** * 标准的原型作用域模式标识。一般的作用域可以通过{@code registerScope}方法注册。 * @see #registerScope */ String SCOPE_PROTOTYPE = "prototype"; /** * 设置bean工厂的父bean工厂。需要注意的是,如果父类bean工厂在工厂初始化的时候,如果不可能, * 应该在构造外部进行设置,这时父类不能改变。 * @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; /** * 设置工厂加载bean类的类加载器。默认为当前线程上下文的类加载器。 * 需要注意的是,如果类的定义还有对应的bean类型解决器,类加载器只能应用于bean的定义。 * 从spring2.0开始,一旦工厂处理bean的定义,仅仅拥有bean类型名字的bean定义才能被解决。 * @param beanClassLoader the class loader to use, * or {@code null} to suggest the default class loader */ void setBeanClassLoader(ClassLoader beanClassLoader); /** * 返回当前bean工厂的类加载器。 */ ClassLoader getBeanClassLoader(); /** * 设置工厂的临时类加载器,一般用于类型匹配的目的。默认为无,简单地使用标准的bean类型加载器。 * 如果处于加载织入时间(load-time weaving),为确保实际的bean类型尽可能的懒加载, * 一个临时的类加载器通常需要指定。一旦在bean工厂启动完成阶段后,临时类加载器将会被移除。 * @since 2.5 */ void setTempClassLoader(ClassLoader tempClassLoader); /** * 返回临时类加载器 * if any. * @since 2.5 */ ClassLoader getTempClassLoader(); /** *设置是否缓存bean的元数据,比如bean的定义,bean类型解决器。默认是缓存。 * 关闭缓存bean元数据,将会开启一些特殊bean定义对象的热刷新。如果关闭缓存, * 任何bean实例创建时,将会重新为新创建的类查询bean类加载器。 */ void setCacheBeanMetadata(boolean cacheBeanMetadata); /** * 返回当前是否缓存bean的元数据。 */ boolean isCacheBeanMetadata(); /** * 设置bean定义中的表达式值的解析器。BeanExpressionResolver * 默认情况下,bean工厂中,是不支持表达式的。应用上下文将会设置一个标准的表达式策略 * 解析器,以统一的Spring EL 兼容形式,支持"#{...}"表达式。 * @since 3.0 */ void setBeanExpressionResolver(BeanExpressionResolver resolver); /** * 获取bean定义中的表达式值的解析器 * @since 3.0 */ BeanExpressionResolver getBeanExpressionResolver(); /** * 设置用于转换bean的属性的转换服务ConversionService。可以作为java bean的属性 * 编辑器PropertyEditors的一种替代。 * @since 3.0 */ void setConversionService(ConversionService conversionService); /** * 获取类型转换服务 * @since 3.0 */ ConversionService getConversionService(); /** * 添加一个属性编辑注册器应用到所有bean的创建过程。 * 属性编辑注册器创建一个属性编辑器实例,并注册到给定的注册器中,并尝试刷新每个bean的创建。 * 注意需要避免与定制编辑器之间的同步,因此一般情况下,最好使用addPropertyEditorRegistrar方法, * 替代{@link #registerCustomEditor}方法。 * @param registrar the PropertyEditorRegistrar to register */ void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); /** * 注册给定的定制属性编辑器到给定类型的所有属性。在工厂配置的过程中调用。 * 注意此方法注册一个共享的定制编辑器实例,可以线程安全地访问编辑器实例。 * 最好使用addPropertyEditorRegistrar方法, 替代{@link #registerCustomEditor}方法。 * 以避免定制编辑器的同步。 * @param requiredType type of the property * @param propertyEditorClass the {@link PropertyEditor} class to register */ void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass); /** * 初始化已经注册到bean工厂的属性编辑注册器与定制编辑器的关系。 * @param registry the PropertyEditorRegistry to initialize */ void copyRegisteredEditorsTo(PropertyEditorRegistry registry); /** * 谁知bean工厂用于bean属性值或构造参数值转换的类型转化器。 * 此方法将会重写默认属性编辑器机制,因此使任何定制编辑器或编辑注册器不相关。 * @see #addPropertyEditorRegistrar * @see #registerCustomEditor * @since 2.5 */ void setTypeConverter(TypeConverter typeConverter); /** * 获取bean工厂的类型转换器。有类型转化器是非线程安全的,每次调用,返回的可能是一个新的实例。 * 如果默认的属性编辑器机制激活,通过返回的类型转换器,可以了解到所有注册的属性编辑器。 * @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); /** * 判断是否注册嵌入值解决器到bean工厂,可以用于{@link #resolveEmbeddedValue(String)}方法。 * @since 4.3 */ boolean hasEmbeddedValueResolver(); /** * 解决给定的嵌入值,比如注解属性 * @param value the value to resolve * @return the resolved value (may be the original value as-is) * @since 3.0 */ String resolveEmbeddedValue(String value); /** * 添加一个bean后处理器,将会用于bean工厂创建的bean。在工厂配置的工厂,将会调用。 * 需要注意的是,bean后处理器处理的顺序与注册的顺序有关;任何实现{@link org.springframework.core.Ordered} * 接口的bean后处理器的排序语义将会被忽略。在程序中注册一个bean后处理器,将会自动探测上下文中的 * bean后处理器。 * @param beanPostProcessor the post-processor to register */ void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); /** * 获取当前注册的bean后处理器数量。时 */ int getBeanPostProcessorCount(); /** * 依赖于给定作用的实现,注册给定的作用域, * @param scopeName the scope identifier * @param scope the backing Scope implementation */ void registerScope(String scopeName, Scope scope); /** * 返回当前注册的作用与的name集。 * 此方法将会返回显示地注册的作用域。 * 单例和原型模式作用域不会暴露。 * @return the array of scope names, or an empty array if none * @see #registerScope */ String[] getRegisteredScopeNames(); /** * 根据给定作用域的name,返回相应的实现。此方法将会返回显示地注册的作用域。 * 单例和原型模式作用域不会暴露。 * @param scopeName the name of the scope * @return the registered Scope implementation, or {@code null} if none * @see #registerScope */ Scope getRegisteredScope(String scopeName); /** * 返回当前工厂相关的安全访问控制上下文java.security.AccessControlContext。 * @return the applicable AccessControlContext (never {@code null}) * @since 3.0 */ AccessControlContext getAccessControlContext(); /** * 从给定的工厂,拷贝所有相关的配置。 * 应包括所有标准的配置,bean后处理器,作用域,工厂内部设置。 * 不包括任何实际bean定义的元数据,比如bean定义对象,bean的别名。 * @param otherFactory the other BeanFactory to copy from */ void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); /** * 创建给定bean name的别名。这个方法支持bean的name,在XML配置中,属于非法,xml只支持ids别名。 * 在工厂配置,经常配置调用,但是也可以使用运行时注册别名。因此,一个工厂的实现, * 应该同步别名访问。 * @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 * 如果别名已经存在,则抛出BeanDefinitionStoreException。 */ void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; /** * 在解决所有目标name的别名和注册到工厂的别名,使用给定的StringValueResolver。 * <p>The value resolver may for example resolve placeholders * in target bean names and even in alias names. * 值解决的例子,比如解决给定bean的名称甚至别名中的占位符。 * @param valueResolver the StringValueResolver to apply * @since 2.5 */ void resolveAliases(StringValueResolver valueResolver); /** * 返回给定bean的名称对应的合并bean定义,如果需要使用它的父工厂合并一个孩子的bean定义。 * 考虑祖先bean工厂中的bean定义。 * @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; /** * 检查给定name的bean是否在工厂中。 * @param name the name of the bean to check * @return whether the bean is a FactoryBean * ({@code false} 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; /** * 显示地控制指定bean的创建状态,仅仅容器内部使用。 * @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); /** * 判断当前bean是否创建。 * @param beanName the name of the bean * @return whether the bean is currently in creation * @since 2.5 */ boolean isCurrentlyInCreation(String beanName); /** * 注册一个依赖bean到给定的bean,在给定bean销毁前销毁依赖的bean。 * @param beanName the name of the bean * @param dependentBeanName the name of the dependent bean * @since 2.5 */ void registerDependentBean(String beanName, String dependentBeanName); /** * 返回依赖于给定bean的所有bean的name。 * @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); /** * 返回给定bean的所有依赖bean的name。 * @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); /** * 根据bean的定义,销毁给定bean的实例,通常为一个原型bean实例。 * 在析构的过程中,任何异常应该被捕捉,同时log,而不是传给方法的调用者。 * @param beanName the name of the bean definition * @param beanInstance the bean instance to destroy */ void destroyBean(String beanName, Object beanInstance); /** * 销毁当前目标作用的指定作用域bean。 * 在析构的过程中,任何异常应该被捕捉,同时log,而不是传给方法的调用者。 * @param beanName the name of the scoped bean */ void destroyScopedBean(String beanName); /** * 销毁所有工厂中的单例bean,包括内部bean,比如已经被注册为disposable的bean。 * 在工厂关闭的时候,将会被调用。 * 在析构的过程中,任何异常应该被捕捉,同时log,而不是传给方法的调用者。 */ void destroySingletons(); }
SingletonBeanRegistry接口源码
package org.springframework.beans.factory.config; /** *SingletonBeanRegistry接口为共享bean实例的注册器。可以被{@link org.springframework.beans.factory.BeanFactory}, *实现,以统一的方式暴露单例管理器。 *ConfigurableBeanFactory接口拓展了此接口 * @author Juergen Hoeller * @since 2.0 * @see ConfigurableBeanFactory * @see org.springframework.beans.factory.support.DefaultSingletonBeanRegistry * @see org.springframework.beans.factory.support.AbstractBeanFactory */ public interface SingletonBeanRegistry { /** * 注册给定存在的单例对象到bean注册器的给定bean的name下。 * 给定的实例,应该完全初始化;注册器不会执行任何初始化回调(在特殊情况下,不会调用 * InitializingBean的 {@code afterPropertiesSet} 方法。 * 给定的实例不会接口任何析构回调(如DisposableBean的{@code destroy}方法)。 * 当一个完全运行的bean工厂的内部,如果bean应该接受初始化和析构回调,应该注册一个bean定义, * 而不是已经存在的实例。 * 在注册配置的过程中,会被调用,但是也可以用在单例运行时注册。因此注册器应该实现单例访问的同步; * 如果支持单例的bean工厂懒加载初始化,不得不实现同步。 * @param beanName the name of the bean * @param singletonObject the existing singleton object * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet * @see org.springframework.beans.factory.DisposableBean#destroy * @see org.springframework.beans.factory.support.BeanDefinitionRegistry#registerBeanDefinition */ void registerSingleton(String beanName, Object singletonObject); /** * 返回给定bean的名称下的注册单例对象。仅仅检查已经初始化的单例对象,而不会返回还没有初始化 * 的单例bean定义。 * 此方法的主要目的为访问手动注册(see {@link #registerSingleton})的单例bean。 * 亦可以用于以bean定义形式的已创建的单例bean定义。 * 需要注意的是:此方法不能识别工厂bean的前缀或别名。在获取单例实例前,必须解决bean的name先。 * @param beanName the name of the bean to look for * @return the registered singleton object, or {@code null} if none found * @see ConfigurableListableBeanFactory#getBeanDefinition */ Object getSingleton(String beanName); /** * 检查当前注册器是否包括给定name的单例实例。仅仅检查已经初始化的单例对象,而不会返回还没有初始化 * 的单例bean定义。 * 此方法的主要目的为访问手动注册(see {@link #registerSingleton})的单例bean。 * 亦可以用于检查是否存在以bean定义形式的已创建的单例bean定义。 * 检查bean工厂是否包含给定name的bean定义,可以使用ListableBeanFactory的{@code containsBeanDefinition} * 方法。使用{@code containsBeanDefinition}和{@code containsSingleton}方法,可以判断bean工厂是否一个 * 本地的bean实例。一般使用bean工厂的 {@code containsBean}方法,检查bean工厂是否知道给定name对应的bean(无论 * 是手动注册的单例bean,还是通过bean定义创建的bean),也可以用于检查祖先工厂 * 需要注意的是:此方法不能识别工厂bean的前缀或别名。在检查单例实例状态前,必须解决bean的name先 * @param beanName the name of the bean to look for * @return if this bean factory contains a singleton instance with the given name * @see #registerSingleton * @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition * @see org.springframework.beans.factory.BeanFactory#containsBean */ boolean containsSingleton(String beanName); /** * 返回注册到注册器的单例bean的name。仅仅检查已经初始化的单例对象,而不会返回还没有初始化 * 的单例bean定义。 * 此方法的主要目的为访问手动注册(see {@link #registerSingleton})的单例bean。 * 亦可以用于检查是否存在以bean定义形式的已创建的单例bean定义。 * @return the list of names as a String array (never {@code null}) * @see #registerSingleton * @see org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinitionNames * @see org.springframework.beans.factory.ListableBeanFactory#getBeanDefinitionNames */ String[] getSingletonNames(); /** * 返回注册到注册器的单例bean数量。仅仅检查已经初始化的单例对象,而不会返回还没有初始化 * 的单例bean定义。 * 此方法的主要目的为访问手动注册(see {@link #registerSingleton})的单例bean。 * 亦可以用于检查是否存在以bean定义形式的已创建的单例bean定义。 * @return the number of singleton beans * @see #registerSingleton * @see org.springframework.beans.factory.support.BeanDefinitionRegistry#getBeanDefinitionCount * @see org.springframework.beans.factory.ListableBeanFactory#getBeanDefinitionCount */ int getSingletonCount(); /** * 返回注册器使用的单例互质锁。 * @return the mutex object (never {@code null}) * @since 4.2 */ Object getSingletonMutex(); }
- HierarchicalBeanFactroy接口:顾名思义,这是一个分层的工厂。该接口实现了Bean工厂的分层。提供了一个非常重要的功能——工厂分层,通过工厂分层,SpringIoC容器可以建立父子层级关联的容器体系,子容器可以访问父容器中的Bean,而父容器不能访问子容器中的Bean。在容器内,Bean的id必须是唯一的,但子容器可以拥有一个和父容器id相同的Bean。父子容器层级体系增强了Spring容器架构的扩展性和灵活性,因为第三方可以通过编程的方式,为一个已经存在的容器添加一个或多个特殊用途的子容器,以提供一些额外的功能,Spring使用父子容器实现了很多功能,比如在Spring MVC中,展现层Bean位于一个子容器中,而业务层和持久层的Bean位于父容器中。这样,展现层Bean就可以引用业务层和持久层的Bean,而业务层和持久层的Bean则看不到展现层的Bean。
- ConfigurableListableBeanFactory接口主要提供了,注册给定自动注入值的依赖类型,决定给定name的对应bean,是否可以作为其他bean中声明匹配的自动依赖注入类型的候选,此操作检查祖先工厂。获取给定name的bean的定义,忽略给定类型或接口的依赖自动注入,获取工厂中的bean的name集操作,同时提供了清除不被考虑的bean的元数据缓存, 冻结bean工厂的bean的定义,判断bean工厂的bean定义是否冻结,以及确保所有非懒加载单例bean被初始化,包括工厂bean相关操作。需要注意的是,bean工厂冻结后,注册的bean定义不能在修改,及进一步的后处理;如果确保所有非懒加载单例bean被初始化失败,记得调用{@link #destroySingletons()}方法,清除已经初始化的单例bean。
/**
* ConfigurableListableBeanFactory是大多数listable bean工厂实现的配置接口,为分析修改bean的定义
* 或单例bean预初始化提供了便利。
* 此接口为bean工厂的子接口,不意味着可以在正常的应用代码中使用,在典型的应用中,使用{@link org.springframework.beans.factory.BeanFactory}
* 或者{@link org.springframework.beans.factory.ListableBeanFactory}。当需要访问bean工厂配置方法时,
* 此接口只允许框架内部使用。
* @author Juergen Hoeller
* @since 03.11.2003
* @see org.springframework.context.support.AbstractApplicationContext#getBeanFactory()
*/
public interface ConfigurableListableBeanFactory
extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
/**
* 忽略给定的依赖类型的自动注入,比如String。默认为无。
* @param type the dependency type to ignore
*/
void ignoreDependencyType(Class<?> type);
/**
* 忽略给定的依赖接口的自动注入。
* 应用上下文注意解决依赖的其他方法,比如通过BeanFactoryAware的BeanFactory,
* 通过ApplicationContextAware的ApplicationContext。
* 默认,仅仅BeanFactoryAware接口被忽略。如果想要更多的类型被忽略,调用此方法即可。
* @param ifc the dependency interface to ignore
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.context.ApplicationContextAware
*/
void ignoreDependencyInterface(Class<?> ifc);
/**
* 注册一个与自动注入值相关的特殊依赖类型。这个方法主要用于,工厂、上下文的引用的自动注入,然而工厂和
* 上下文的实例bean,并不工厂中:比如应用上下文的依赖,可以解决应用上下文实例中的bean。
* 需要注意的是:在一个空白的bean工厂中,没有这种默认的类型注册,设置没有bean工厂接口字节。
* @param dependencyType
* 需要注册的依赖类型。典型地使用,比如一个bean工厂接口,只要给定的自动注入依赖是bean工厂的拓展即可,
* 比如ListableBeanFactory。
* @param autowiredValue
* 相关的自动注入的值。也许是一个对象工厂{@link org.springframework.beans.factory.ObjectFactory}的实现,
* 运行懒加载方式解决实际的目标值。
*/
void registerResolvableDependency(Class<?> dependencyType, Object autowiredValue);
/**
* 决定给定name的对应bean,是否可以作为其他bean中声明匹配的自动依赖注入类型的候选。此方法检查祖先工厂。
* @param beanName the name of the bean to check
* 需要检查的bean的name
* @param descriptor the descriptor of the dependency to resolve
* 依赖描述
* @return whether the bean should be considered as autowire candidate
* 返回bean是否为自动注入的候选
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
*/
boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
throws NoSuchBeanDefinitionException;
/**
* 返回给定bean的bean定义,运行访问bean的属性值和构造参数(可以在bean工厂后处理器处理的过程中修改)。
* 返回的bean定义不应该为bean定义的copy,而是原始注册到bean工厂的bean的定义。意味着,如果需要,
* 应该投射到一个更精确的类型。
* 此方法不考虑祖先工厂。即只能访问当前工厂中bean定义。
* @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;
/**
* 返回当前工厂中的所有bean的name的统一视图集。
* 包括bean的定义,及自动注册的单例bean实例,首先bean定义与bean的name一致,然后根据类型、注解检索bean的name。
* @return the composite iterator for the bean names view
* @since 4.1.2
* @see #containsBeanDefinition
* @see #registerSingleton
* @see #getBeanNamesForType
* @see #getBeanNamesForAnnotation
*/
Iterator<String> getBeanNamesIterator();
/**
* 清除整合bean定义的缓存,移除还没有缓存所有元数据的bean。
* 典型的触发场景,在原始的bean定义修改之后,比如应用 {@link BeanFactoryPostProcessor}。需要注意的是,
* 在当前时间点,bean定义已经存在的元数据将会被保存。
* @since 4.2
* @see #getBeanDefinition
* @see #getMergedBeanDefinition
*/
void clearMetadataCache();
/**
* 冻结所有bean定义,通知上下文,注册的bean定义不能在修改,及进一步的后处理。
* <p>This allows the factory to aggressively cache bean definition metadata.
*/
void freezeConfiguration();
/**
* 返回bean工厂中的bean定义是否已经冻结。即不应该修改和进一步的后处理。
* @return {@code true} if the factory's configuration is considered frozen
* 如果冻结,则返回true。
*/
boolean isConfigurationFrozen();
/**
* 确保所有非懒加载单例bean被初始化,包括工厂bean{@link org.springframework.beans.factory.FactoryBean FactoryBeans}。
* Typically invoked at the end of factory setup, if desired.
* 如果需要,在bean工厂设置后,调用此方法。
* @throws BeansException
* 如果任何一个单例bean不能够创建,将抛出BeansException。
* 需要注意的是:操作有可能遗留一些已经初始化的bean,可以调用{@link #destroySingletons()}完全清楚。
* @see #destroySingletons()
*/
void preInstantiateSingletons() throws BeansException;
}
Bean工厂的抽象现实基类:AbstractBeanFactory抽象类
AbstractBeanFactory这个抽象类是Spring容器体系中最重要的一个抽象类,该抽象类实现了BeanFactory重要的二级接口ConfigurableBeanFactory,实现了其中的绝大多数基本方法,实现了Bean工厂的许多重要功能,如对BeanDefinition、原型、单例Bean的各种操作。AbstractBeanFactory源码自己看,逻辑方法太多了,只列几个具体→
AbstractBeanFactory源码字段
// 父类容器 private BeanFactory parentBeanFactory; // 类加载器 private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); // 临时加载器 private ClassLoader tempClassLoader; // bean的元数据缓存 private boolean cacheBeanMetadata = true; // bean的表达式解析器 private BeanExpressionResolver beanExpressionResolver; // 类型转换器 private ConversionService conversionService; // 属性编辑器 private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4); // 类的属性编辑器 private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4); // 类型转换器 private TypeConverter typeConverter; // 为嵌入的值(如注释属性)添加字符串解析器 private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>(); // 后置处理器 private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>(); // InstantiationAwareBeanPostProcessors是否已注册 private volatile boolean hasInstantiationAwareBeanPostProcessors; // DestructionAwareBeanPostProcessors是否已注册 private volatile boolean hasDestructionAwareBeanPostProcessors; // 作用域 private final Map<String, Scope> scopes = new LinkedHashMap<>(8); // 提供安全作用域 private SecurityContextProvider securityContextProvider; // 合并后的BeanDefinition private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256); // bean实例是否已创建 private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256)); // 本地缓存,正在创建的多例bean。这边用本地线程,是因为其他线程创建bean与当前线程不冲突 private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<>("Prototype beans currently in creation");
方法
构造函数,父类容器可作为参数传入 public AbstractBeanFactory() { } **doGetBean参数:** name:bean的名称 requiredType: 返回的类型 args: 传递的构造参数 typeCheckOnly: 检查类型 public AbstractBeanFactory(@Nullable BeanFactory parentBeanFactory) { this.parentBeanFactory = parentBeanFactory; } protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { //获取beanName,这边有三种形式,一个是原始的beanName,一个是加了&的,一个是别名 final String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. // 是否已经创建了 Object sharedInstance = getSingleton(beanName); //已经创建了,且没有构造参数,进入这个方法,如果有构造参数,往else走,也就是说不从获取bean,而直接创建bean if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } // 如果是普通bean,直接返回,是FactoryBean,返回他的getObject bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. // 没创建过bean或者是多例的情况或者有参数的情况 // 创建过Prototype的bean,会循环引用,抛出异常,单例才尝试解决循环依赖的问题 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); // 父容器存在,本地没有当前beanName,从父容器取 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. // 处理后,如果是加&,就补上& String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } } if (!typeCheckOnly) { // typeCheckOnly为false,将beanName放入alreadyCreated中 markBeanAsCreated(beanName); } try { // 获取BeanDefinition final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // 抽象类检查 checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. // 如果有依赖的情况,先初始化依赖的bean String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { // 检查是否循环依赖,a依赖b,b依赖a。包括传递的依赖,比如a依赖b,b依赖c,c依赖a if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 注册依赖关系 registerDependentBean(dep, beanName); try { // 初始化依赖的bean getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // Create bean instance. // 如果是单例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { // 创建bean return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); // 如果是普通bean,直接返回,是FactoryBean,返回他的getObject bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { // 加入prototypesCurrentlyInCreation,说明正在创建 beforePrototypeCreation(beanName); //创建bean prototypeInstance = createBean(beanName, mbd, args); } finally { // 移除prototypesCurrentlyInCreation,说明已经创建结束 afterPrototypeCreation(beanName); } // 如果是普通bean,直接返回,是FactoryBean,返回他的getObject bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // Check if required type matches the type of the actual bean instance. if (requiredType != null && !requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isTraceEnabled()) { logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; } containsBean 是否已经创建bean或者定义好了bean,包括当前容器以及父容器 public boolean containsBean(String name) { String beanName = transformedBeanName(name); // 已创建单例bean或者包括bean的定义 if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { // 如果不是&开头的,直接返回 // 如果是&开头的,判断是否是FactoryBean,没有找到从父类找 return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name)); } // Not found -> check parent. // 当前容器没找到,去父类找 BeanFactory parentBeanFactory = getParentBeanFactory(); return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name))); } isSingleton 指定beanName是否是单例,包括普通的bean和FactoryBean,包括当前容器以及父容器 public boolean isSingleton(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // 如果已经实例化了 Object beanInstance = getSingleton(beanName, false); if (beanInstance != null) { if (beanInstance instanceof FactoryBean) { // 是FactoryBean类型,name要&开头或者FactoryBean中isSingleton方法返回为true return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton()); } else { // 如果不是FactoryBean,name就不能是&开头 return !BeanFactoryUtils.isFactoryDereference(name); } } // No singleton instance found -> check bean definition. // 如果当前容器还没实例化,去父类找 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isSingleton(originalBeanName(name)); } // 父类也没有,根据定义来判断是否是单例 // 获取合并后的BeanDefinition RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // In case of FactoryBean, return singleton status of created object if not a dereference. if (mbd.isSingleton()) { // 如果定义了是单例,判断是否是FactoryBean,如果是FactoryBean,name就要是&开头 if (isFactoryBean(beanName, mbd)) { if (BeanFactoryUtils.isFactoryDereference(name)) { return true; } // 如果是单例,但是name不是&开头,就重新获取factoryBean,再判断是否是单例 FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); return factoryBean.isSingleton(); } else { // 如果不是FactoryBean,就不能是&开头 return !BeanFactoryUtils.isFactoryDereference(name); } } else { return false; } } isPrototype 指定beanName是否是多例,包括普通的bean和FactoryBean,包括当前容器以及父容器 public boolean isPrototype(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // 有父容器,且没有beanName的定义,从父容器中查找 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isPrototype(originalBeanName(name)); } // 没有再从当前容器查找 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (mbd.isPrototype()) { // In case of FactoryBean, return singleton status of created object if not a dereference. // 如果是普通的bean返回true,如果是&开头的,且是FactoryBean,返回true return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd)); } // Singleton or scoped - not a prototype. // However, FactoryBean may still produce a prototype object... // 如果不是Prototype,且是&开头,&开头就是FactoryBean,FactoryBean是单例的,所以是返回false if (BeanFactoryUtils.isFactoryDereference(name)) { return false; } // 如果是FactoryBean,判断是否有Singleton或者Prototype if (isFactoryBean(beanName, mbd)) { final FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); if (System.getSecurityManager() != null) { return AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton()), getAccessControlContext()); } else { return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) || !fb.isSingleton()); } } else { return false; } } isTypeMatch 指定的beanName是否与类型匹配 public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. // 获取单例 Object beanInstance = getSingleton(beanName, false); // 不为空并且不是NullBean类型 if (beanInstance != null && beanInstance.getClass() != NullBean.class) { if (beanInstance instanceof FactoryBean) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // 不是&开头,获取FactoryBean的getObjectType类型,再来比较 Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance); return (type != null && typeToMatch.isAssignableFrom(type)); } else { // name是&开头,直接判断类型FactoryBean return typeToMatch.isInstance(beanInstance); } } // 普通bean,且没有&开头 else if (!BeanFactoryUtils.isFactoryDereference(name)) { if (typeToMatch.isInstance(beanInstance)) { // Direct match for exposed instance? return true; } // 泛型且有beanName的定义 else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) { // Generics potentially only match on the target class, not on the proxy... // 合并定义 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> targetType = mbd.getTargetType(); if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) { // Check raw class match as well, making sure it's exposed on the proxy. Class<?> classToMatch = typeToMatch.resolve(); if (classToMatch != null && !classToMatch.isInstance(beanInstance)) { return false; } if (typeToMatch.isAssignableFrom(targetType)) { return true; } } ResolvableType resolvableType = mbd.targetType; if (resolvableType == null) { resolvableType = mbd.factoryMethodReturnType; } return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType)); } } return false; } // 已经创建了,但是没有bean的定义,说明是空的注册进来 else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) { // null instance registered return false; } // No singleton instance found -> check bean definition. // 从父类找 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch); } // Retrieve corresponding bean definition. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> classToMatch = typeToMatch.resolve(); if (classToMatch == null) { classToMatch = FactoryBean.class; } Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ? new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch}); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return typeToMatch.isAssignableFrom(targetClass); } } Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch); if (beanType == null) { return false; } // Check bean class whether we're dealing with a FactoryBean. if (FactoryBean.class.isAssignableFrom(beanType)) { if (!BeanFactoryUtils.isFactoryDereference(name) && beanInstance == null) { // If it's a FactoryBean, we want to look at what it creates, not the factory class. beanType = getTypeForFactoryBean(beanName, mbd); if (beanType == null) { return false; } } } else if (BeanFactoryUtils.isFactoryDereference(name)) { // Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean // type but we nevertheless are being asked to dereference a FactoryBean... // Let's check the original bean class and proceed with it if it is a FactoryBean. beanType = predictBeanType(beanName, mbd, FactoryBean.class); if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) { return false; } } ResolvableType resolvableType = mbd.targetType; if (resolvableType == null) { resolvableType = mbd.factoryMethodReturnType; } if (resolvableType != null && resolvableType.resolve() == beanType) { return typeToMatch.isAssignableFrom(resolvableType); } return typeToMatch.isAssignableFrom(beanType); } public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException { // 类型转换后调用上面的方法 return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch)); } getType 获取指定beanName的类型 public Class<?> getType(String name) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); // Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); // 已经实例化并且不是NullBean if (beanInstance != null && beanInstance.getClass() != NullBean.class) { // 如果是FactoryBean,且没有&,说明是取FactoryBean的getObjectType类型 if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { return getTypeForFactoryBean((FactoryBean<?>) beanInstance); } else { // 直接返回类型 return beanInstance.getClass(); } } // No singleton instance found -> check bean definition. // 没有实例过,从父容器看看有没有实例化 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.getType(originalBeanName(name)); } // 都没有实例化,从定义里查找 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass; } } Class<?> beanClass = predictBeanType(beanName, mbd); // Check bean class whether we're dealing with a FactoryBean. if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class. return getTypeForFactoryBean(beanName, mbd); } else { return beanClass; } } else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null); } } getBeanClassLoader类加载器、临时加载器 // 设置类加载器 public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) { this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader()); } // 获取类加载器 public ClassLoader getBeanClassLoader() { return this.beanClassLoader; } // 设置临时加载器,如果涉及到加载时编织,通常只指定一个临时类装入器,以确保实际的bean类被尽可能延迟地装入 public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) { this.tempClassLoader = tempClassLoader; } // 获取临时加载器 public ClassLoader getTempClassLoader() { return this.tempClassLoader; } isCacheBeanMetadata bean的元数据缓存,默认为true。如果为false,每次创建bean都要从类加载器获取信息 // 设置是否缓存 public void setCacheBeanMetadata(boolean cacheBeanMetadata) { this.cacheBeanMetadata = cacheBeanMetadata; } // 获取是否缓存 public boolean isCacheBeanMetadata() { return this.cacheBeanMetadata; } getTypeConverter 类型转换器 // 设置类型转换器 public void setTypeConverter(TypeConverter typeConverter) { this.typeConverter = typeConverter; } // 获取自定义的类型转换器,这边直接取类型转换器 protected TypeConverter getCustomTypeConverter() { return this.typeConverter; } // 获取类型转换器 public TypeConverter getTypeConverter() { TypeConverter customConverter = getCustomTypeConverter(); if (customConverter != null) { return customConverter; } else { // Build default TypeConverter, registering custom editors. // 没有设值就初始化一个SimpleTypeConverter SimpleTypeConverter typeConverter = new SimpleTypeConverter(); typeConverter.setConversionService(getConversionService()); registerCustomEditors(typeConverter); return typeConverter; } } 后置器 // 增加后置处理器 public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null"); // Remove from old position, if any // 移除旧的,保证顺序 this.beanPostProcessors.remove(beanPostProcessor); // Track whether it is instantiation/destruction aware // 如果是下面两个类型,标志位就设置true if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } // Add to end of list this.beanPostProcessors.add(beanPostProcessor); } // 获取后置处理器的个数 public int getBeanPostProcessorCount() { return this.beanPostProcessors.size(); } // 获取后置处理器 public List<BeanPostProcessor> getBeanPostProcessors() { return this.beanPostProcessors; }
AbstractBeanFactory的继承关系
- AbstractBeanFactory其实还继承了另外一个抽象类——
FactoryBeanRegistrySupport
- AbstractBeanFactory另一个继承关系
这个继承体系是Spring的AliasRegistry体系,也就是别名注册接口体系
AbstractBeanFactory既然继承了这个体系,说明容器本身也是个别名注册器、FactroyBean注册器和单例Bean注册器,也会维护别名注册表、支持FactroyBean的注册和单例Bean注册的各种操作(注册、获取、移除、销毁等)。
- AbstractBeanFactory其实还继承了另外一个抽象类——
第一个可以独立运行的容器实现类——DefaultListableBeanFactory类
DefaultListableBeanFactory类是Spring提供的默认简单容器实现类,也是从BeanFactory接口一路继承与实现下来的第一个可以独立运行的容器类,该类间接继承了AbstractBeanFactory抽象类,同时还实现了Spring集大成的容器接口——ConfigurableListableBeanFactory 接口,这保证了DefaultListableBeanFactory完整实现了简单容器中对Bean的各种操作功能。
而且我们还在源码中发现,DefaultListableBeanFactory同时还实现了BeanDefinitionRegistry接口,关于这个接口的具体介绍见:向容器中注册BeanDefinition——BeanDefinitionRegistry。正是因为实现了此接口,所以DefaultListableBeanFactory也是一个BeanDefinition注册器,拥有了注册BeanDefinition的作用。可以从源码中发现,DefaultListableBeanFactory中维护了一个beanDefinitionMap,即BeanDefinition注册表。源码解析
字段
// JSR-330 支持 private static Class<?> javaxInjectProviderClass; // DefaultListableBeanFactory引用的缓存 private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories = new ConcurrentHashMap<>(8); // 序列号id private String serializationId; // 是否允许用相同的名称重新注册不同的定义 private boolean allowBeanDefinitionOverriding = true; // 是否允许懒加载 private boolean allowEagerClassLoading = true; // 依赖排序顺序 private Comparator<Object> dependencyComparator; // 解析器,用于检查bean定义是否为自动装配候选 private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver(); // 依赖类型和自动注入值的映射 private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16); // BeanDefinition和beanName的映射 private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256); // 依赖类型和单例、非单例bean的映射 private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64); // 依赖类型和单例bean的映射 private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64); // bean定义名称列表,按注册顺序排列。 private volatile List<String> beanDefinitionNames = new ArrayList<>(256); // 手动注册的单例,按注册顺序排列 private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16); // 固定配置的缓存的bean定义名数组 private volatile String[] frozenBeanDefinitionNames; // 是否可以缓存所有bean的bean定义元数据 private volatile boolean configurationFrozen = false;
方法
//构造方法 public DefaultListableBeanFactory() { super(); } public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) { super(parentBeanFactory); } //序列号设置,同时设置到serializableFactories中 public void setSerializationId(@Nullable String serializationId) { if (serializationId != null) { serializableFactories.put(serializationId, new WeakReference<>(this)); } else if (this.serializationId != null) { serializableFactories.remove(this.serializationId); } this.serializationId = serializationId; } public String getSerializationId() { return this.serializationId; } //get、set略过 //复制其他配置信息 public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { super.copyConfigurationFrom(otherFactory); if (otherFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory; this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding; this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading; this.dependencyComparator = otherListableFactory.dependencyComparator; // A clone of the AutowireCandidateResolver since it is potentially BeanFactoryAware... setAutowireCandidateResolver(BeanUtils.instantiateClass(getAutowireCandidateResolver().getClass())); // Make resolvable dependencies (e.g. ResourceLoader) available here as well... this.resolvableDependencies.putAll(otherListableFactory.resolvableDependencies); } } //获取bean public <T> T getBean(Class<T> requiredType) throws BeansException { // 根据class类型获取bean return getBean(requiredType, (Object[]) null); } public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException { Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return (T) resolved; } //获取bean的提供者 public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) throws BeansException { return getBeanProvider(ResolvableType.forRawClass(requiredType)); } public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) { return new BeanObjectProvider<T>() { @Override public T getObject() throws BeansException { T resolved = resolveBean(requiredType, null, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return resolved; } @Override public T getObject(Object... args) throws BeansException { T resolved = resolveBean(requiredType, args, false); if (resolved == null) { throw new NoSuchBeanDefinitionException(requiredType); } return resolved; } @Override @Nullable public T getIfAvailable() throws BeansException { return resolveBean(requiredType, null, false); } @Override @Nullable public T getIfUnique() throws BeansException { return resolveBean(requiredType, null, true); } @Override public Stream<T> stream() { return Arrays.stream(getBeanNamesForTypedStream(requiredType)) .map(name -> (T) getBean(name)) .filter(bean -> !(bean instanceof NullBean)); } @Override public Stream<T> orderedStream() { String[] beanNames = getBeanNamesForTypedStream(requiredType); Map<String, T> matchingBeans = new LinkedHashMap<>(beanNames.length); for (String beanName : beanNames) { Object beanInstance = getBean(beanName); if (!(beanInstance instanceof NullBean)) { matchingBeans.put(beanName, (T) beanInstance); } } Stream<T> stream = matchingBeans.values().stream(); return stream.sorted(adaptOrderComparator(matchingBeans)); } }; } //bean的解析 private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) { NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull); if (namedBean != null) { return namedBean.getBeanInstance(); } BeanFactory parent = getParentBeanFactory(); // 如果父类是DefaultListableBeanFactory,调用父类的resolveBean方法 if (parent instanceof DefaultListableBeanFactory) { return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull); } else if (parent != null) { // 如果父类不是DefaultListableBeanFactory,且不为空,获取父类的bean的提供者 ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType); if (args != null) { // 有参构造 return parentProvider.getObject(args); } else { // 无参构造,getIfAvailable:实际存在才返回一个实例,* getIfUnique: 有多个实例时,返回默认的实例(比如primary) return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable()); } } return null; } //通过ResolvableType获取bean名称 private String[] getBeanNamesForTypedStream(ResolvableType requiredType) { return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this, requiredType); } //检查此bean工厂是否包含具有指定名称的bean定义。 public boolean containsBeanDefinition(String beanName) { Assert.notNull(beanName, "Bean name must not be null"); return this.beanDefinitionMap.containsKey(beanName); } //获取bean定义的个数 public int getBeanDefinitionCount() { return this.beanDefinitionMap.size(); } //不考虑此工厂可能参与的任何层次结构,并且忽略通过bean定义以外的其他方式注册的任何单例bean public String[] getBeanDefinitionNames() { String[] frozenNames = this.frozenBeanDefinitionNames; if (frozenNames != null) { return frozenNames.clone(); } else { return StringUtils.toStringArray(this.beanDefinitionNames); } } //根据bean定义或factorybean中getObjectType的值判断,返回与给定类型(包括子类)匹配的bean的名称。 public String[] getBeanNamesForType(ResolvableType type) { Class<?> resolved = type.resolve(); if (resolved != null && !type.hasGenerics()) { return getBeanNamesForType(resolved, true, true); } else { return doGetBeanNamesForType(type, true, true); } } public String[] getBeanNamesForType(@Nullable Class<?> type) { return getBeanNamesForType(type, true, true); } @Override public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) { if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit); } Map<Class<?>, String[]> cache = (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType); String[] resolvedBeanNames = cache.get(type); if (resolvedBeanNames != null) { return resolvedBeanNames; } resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true); if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) { cache.put(type, resolvedBeanNames); } return resolvedBeanNames; } //根据bean定义或factorybean中getObjectType的值判断,返回与给定类型(包括子类)匹配的bean的名称。 private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) { List<String> result = new ArrayList<>(); // Check all bean definitions. // 遍历所有的beanName for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name // is not defined as alias for some other bean. // 没有别名 if (!isAlias(beanName)) { try { // 合并bean的定义 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); // Only check bean definition if it is complete. if (!mbd.isAbstract() && (allowEagerInit || (mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) && !requiresEagerInitForType(mbd.getFactoryBeanName()))) { // In case of FactoryBean, match object created by FactoryBean. // 是否是FactoryBean boolean isFactoryBean = isFactoryBean(beanName, mbd); BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); boolean matchFound = (allowEagerInit || !isFactoryBean || (dbd != null && !mbd.isLazyInit()) || containsSingleton(beanName)) && (includeNonSingletons || (dbd != null ? mbd.isSingleton() : isSingleton(beanName))) && isTypeMatch(beanName, type); if (!matchFound && isFactoryBean) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX + beanName; matchFound = (includeNonSingletons || mbd.isSingleton()) && isTypeMatch(beanName, type); } if (matchFound) { result.add(beanName); } } } catch (CannotLoadBeanClassException ex) { if (allowEagerInit) { throw ex; } // Probably a class name with a placeholder: let's ignore it for type matching purposes. if (logger.isTraceEnabled()) { logger.trace("Ignoring bean class loading failure for bean '" + beanName + "'", ex); } onSuppressedException(ex); } catch (BeanDefinitionStoreException ex) { if (allowEagerInit) { throw ex; } // Probably some metadata with a placeholder: let's ignore it for type matching purposes. if (logger.isTraceEnabled()) { logger.trace("Ignoring unresolvable metadata in bean definition '" + beanName + "'", ex); } onSuppressedException(ex); } } } // Check manually registered singletons too. for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean(beanName)) { if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) { result.add(beanName); // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX + beanName; } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add(beanName); } } catch (NoSuchBeanDefinitionException ex) { // Shouldn't happen - probably a result of circular reference resolution... if (logger.isTraceEnabled()) { logger.trace("Failed to check manually registered singleton with name '" + beanName + "'", ex); } } } return StringUtils.toStringArray(result); } //是否马上返回bean以确定类型 private boolean requiresEagerInitForType(@Nullable String factoryBeanName) { return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName)); } //获取bean名称和实例的映射 public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException { return getBeansOfType(type, true, true); } public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { // 根据类型获取到bean名称 String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); Map<String, T> result = new LinkedHashMap<>(beanNames.length); // 遍历所有名称,通过bean名称获取实例,如果不是NullBean加入到result for (String beanName : beanNames) { try { Object beanInstance = getBean(beanName); if (!(beanInstance instanceof NullBean)) { result.put(beanName, (T) beanInstance); } } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException) { BeanCreationException bce = (BeanCreationException) rootCause; String exBeanName = bce.getBeanName(); if (exBeanName != null && isCurrentlyInCreation(exBeanName)) { if (logger.isTraceEnabled()) { logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " + ex.getMessage()); } onSuppressedException(ex); // Ignore: indicates a circular reference when autowiring constructors. // We want to find matches other than the currently created bean itself. continue; } } throw ex; } } return result; } //根据注解获取bean的名称 public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) { List<String> result = new ArrayList<>(); // 遍历所有的bean的,把不是抽象类的,以及有annotationType注解的加入到result for (String beanName : this.beanDefinitionNames) { BeanDefinition beanDefinition = getBeanDefinition(beanName); if (!beanDefinition.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) { result.add(beanName); } } // 遍历所有的manualSingletonNames,把没有加入到result的以及有annotationType注解的加入到result for (String beanName : this.manualSingletonNames) { if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) { result.add(beanName); } } return StringUtils.toStringArray(result); } //根据注解获取bean的实例 public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) { // 根据注解获取bean的名称 String[] beanNames = getBeanNamesForAnnotation(annotationType); Map<String, Object> result = new LinkedHashMap<>(beanNames.length); // 遍历bean的名称,获取bean的实例 for (String beanName : beanNames) { Object beanInstance = getBean(beanName); if (!(beanInstance instanceof NullBean)) { result.put(beanName, beanInstance); } } return result; } //根据beanName获取注解 public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) throws NoSuchBeanDefinitionException { A ann = null; // 获取class Class<?> beanType = getType(beanName); if (beanType != null) { // class不为空,获取注解 ann = AnnotationUtils.findAnnotation(beanType, annotationType); } // 没获取到注解,且有定义过,从定义里的beanClass获取 if (ann == null && containsBeanDefinition(beanName)) { BeanDefinition bd = getMergedBeanDefinition(beanName); if (bd instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) bd; if (abd.hasBeanClass()) { ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType); } } } return ann; } //注册依赖类型和自动注入值 public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) { Assert.notNull(dependencyType, "Dependency type must not be null"); if (autowiredValue != null) { if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) { throw new IllegalArgumentException("Value [" + autowiredValue + "] does not implement specified dependency type [" + dependencyType.getName() + "]"); } this.resolvableDependencies.put(dependencyType, autowiredValue); } } //指定的bean是否是自动注入的候选 public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor) throws NoSuchBeanDefinitionException { return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver()); } protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) throws NoSuchBeanDefinitionException { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); // 定义过的,从定义里找 if (containsBeanDefinition(beanDefinitionName)) { return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName), descriptor, resolver); } // 创建过的单例,重新创建RootBeanDefinition else if (containsSingleton(beanName)) { return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver); } // 都没找到,从父类找 BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { // No bean definition found in this factory -> delegate to parent. return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver); } else if (parent instanceof ConfigurableListableBeanFactory) { // If no DefaultListableBeanFactory, can't pass the resolver along. return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor); } else { return true; } } protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd, DependencyDescriptor descriptor, AutowireCandidateResolver resolver) { String beanDefinitionName = BeanFactoryUtils.transformedBeanName(beanName); // 解析 resolveBeanClass(mbd, beanDefinitionName); if (mbd.isFactoryMethodUnique && mbd.factoryMethodToIntrospect == null) { new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd); } // 从别名里找 return resolver.isAutowireCandidate( new BeanDefinitionHolder(mbd, beanName, getAliases(beanDefinitionName)), descriptor); } //从beanDefinitionMap找bean的定义 public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { BeanDefinition bd = this.beanDefinitionMap.get(beanName); if (bd == null) { if (logger.isTraceEnabled()) { logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } return bd; } //获取bean的迭代名称,包括自定的和手动注册的 public Iterator<String> getBeanNamesIterator() { CompositeIterator<String> iterator = new CompositeIterator<>(); iterator.add(this.beanDefinitionNames.iterator()); iterator.add(this.manualSingletonNames.iterator()); return iterator; } //清理元数据缓存 public void clearMetadataCache() { super.clearMetadataCache(); clearByTypeCache(); } //冻结当前的bean的信息 public void freezeConfiguration() { this.configurationFrozen = true; this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames); } //配置冻结 public boolean isConfigurationFrozen() { return this.configurationFrozen; } //是否已经冻结了或者是否已创建 protected boolean isBeanEligibleForMetadataCaching(String beanName) { return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName)); } //确保实例化了所有非lazy-init单例 public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... // 遍历beanNames for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 不是抽象的,并且是单例且没有懒加载 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //FactoryBean的情况,加&获取 if (isFactoryBean(beanName)) { Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { final FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } } else { // 不是FactoryBean直接获取 getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... // 获取单例bean后,如果是SmartInitializingSingleton类型,再调用afterSingletonsInstantiated方法 for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } } //把beanName和beanDefinition放入beanDefinitionMap中 public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); if (beanDefinition instanceof AbstractBeanDefinition) { try { // 注册前的检查,主要检查methodOverrides,methodOverrides和factoryBeanName不能共存 // methodOverrides对应的方法,要存在 ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } // 获取bean的定义 BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); // 存在的情况 if (existingDefinition != null) { // 不允许覆盖,抛异常 if (!isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition); } // 比如是ROLE_APPLICATION,给用户使用的,新的确是ROLE_SUPPORT,完全内部使用,就抛异常 else if (existingDefinition.getRole() < beanDefinition.getRole()) { // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (logger.isInfoEnabled()) { logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } // 参考AbstractBeanDefinition的equals方法 else if (!beanDefinition.equals(existingDefinition)) { if (logger.isDebugEnabled()) { logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } else { if (logger.isTraceEnabled()) { logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]"); } } // 注册beanDefinition this.beanDefinitionMap.put(beanName, beanDefinition); } else { // 不存在的情况,有bean创建了 if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) // 加锁,注册beanDefinition,记录beanDefinitionNames,如果有手动注册的记录,则移除 synchronized (this.beanDefinitionMap) { this.beanDefinitionMap.put(beanName, beanDefinition); List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase // 注册beanDefinition,记录beanDefinitionNames,如果有手动注册的记录,则移除 this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } // 有注册过,固定冻结的记录则清空 this.frozenBeanDefinitionNames = null; } // 重置beanName的缓存 if (existingDefinition != null || containsSingleton(beanName)) { resetBeanDefinition(beanName); } } //移除bean public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException { Assert.hasText(beanName, "'beanName' must not be empty"); // 移除 BeanDefinition bd = this.beanDefinitionMap.remove(beanName); // 为空说明之前不存在 if (bd == null) { if (logger.isTraceEnabled()) { logger.trace("No bean named '" + beanName + "' found in " + this); } throw new NoSuchBeanDefinitionException(beanName); } // 已经创建bean了,要加锁 if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames); updatedDefinitions.remove(beanName); this.beanDefinitionNames = updatedDefinitions; } } else { // Still in startup registration phase // 还没创建,直接移除 this.beanDefinitionNames.remove(beanName); } this.frozenBeanDefinitionNames = null; resetBeanDefinition(beanName); } //重置bean的定义 protected void resetBeanDefinition(String beanName) { // Remove the merged bean definition for the given bean, if already created. // bean定义删除 clearMergedBeanDefinition(beanName); // Remove corresponding bean from singleton cache, if any. Shouldn't usually // be necessary, rather just meant for overriding a context's default beans // (e.g. the default StaticMessageSource in a StaticApplicationContext). // bean销毁 destroySingleton(beanName); // Notify all post-processors that the specified bean definition has been reset. for (BeanPostProcessor processor : getBeanPostProcessors()) { if (processor instanceof MergedBeanDefinitionPostProcessor) { ((MergedBeanDefinitionPostProcessor) processor).resetBeanDefinition(beanName); } } // Reset all bean definitions that have the given bean as parent (recursively). // 子类重置 for (String bdName : this.beanDefinitionNames) { if (!beanName.equals(bdName)) { BeanDefinition bd = this.beanDefinitionMap.get(bdName); if (beanName.equals(bd.getParentName())) { resetBeanDefinition(bdName); } } } } //注册单例,手动注册的单例,保存在manualSingletonNames public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { super.registerSingleton(beanName, singletonObject); if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { if (!this.beanDefinitionMap.containsKey(beanName)) { Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1); updatedSingletons.addAll(this.manualSingletonNames); updatedSingletons.add(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase if (!this.beanDefinitionMap.containsKey(beanName)) { this.manualSingletonNames.add(beanName); } } clearByTypeCache(); } //销毁bean,还要移除manualSingletonNames的bean public void destroySingleton(String beanName) { super.destroySingleton(beanName); this.manualSingletonNames.remove(beanName); clearByTypeCache(); } //销毁所有bean,还要移除manualSingletonNames的所有bean public void destroySingletons() { super.destroySingletons(); this.manualSingletonNames.clear(); clearByTypeCache(); } //清除依赖类型的映射 private void clearByTypeCache() { this.allBeanNamesByType.clear(); this.singletonBeanNamesByType.clear(); } //通过类型解析bean public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException { NamedBeanHolder<T> namedBean = resolveNamedBean(ResolvableType.forRawClass(requiredType), null, false); if (namedBean != null) { return namedBean; } // 为空去父类查找 BeanFactory parent = getParentBeanFactory(); if (parent instanceof AutowireCapableBeanFactory) { return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType); } throw new NoSuchBeanDefinitionException(requiredType); } private <T> NamedBeanHolder<T> resolveNamedBean( ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException { Assert.notNull(requiredType, "Required type must not be null"); // 获取候选bean String[] candidateNames = getBeanNamesForType(requiredType); if (candidateNames.length > 1) { List<String> autowireCandidates = new ArrayList<>(candidateNames.length); for (String beanName : candidateNames) { if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) { autowireCandidates.add(beanName); } } if (!autowireCandidates.isEmpty()) { candidateNames = StringUtils.toStringArray(autowireCandidates); } } // 只有一个候选,就确定是这个了 if (candidateNames.length == 1) { String beanName = candidateNames[0]; return new NamedBeanHolder<>(beanName, (T) getBean(beanName, requiredType.toClass(), args)); } else if (candidateNames.length > 1) { Map<String, Object> candidates = new LinkedHashMap<>(candidateNames.length); for (String beanName : candidateNames) { // 无参,直接获取bean的类型 if (containsSingleton(beanName) && args == null) { Object beanInstance = getBean(beanName); candidates.put(beanName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { // 有参,通过beanName获取类型 candidates.put(beanName, getType(beanName)); } } // 获取主要的一个 String candidateName = determinePrimaryCandidate(candidates, requiredType.toClass()); if (candidateName == null) { // 没获取到,从最高级的获取 candidateName = determineHighestPriorityCandidate(candidates, requiredType.toClass()); } if (candidateName != null) { // 获取到了,创建一个NamedBeanHolder返回 Object beanInstance = candidates.get(candidateName); if (beanInstance == null || beanInstance instanceof Class) { beanInstance = getBean(candidateName, requiredType.toClass(), args); } return new NamedBeanHolder<>(candidateName, (T) beanInstance); } if (!nonUniqueAsNull) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet()); } } return null; } //根据工厂中定义的bean解析指定的依赖项 public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) { return createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class == descriptor.getDependencyType() || ObjectProvider.class == descriptor.getDependencyType()) { return new DependencyObjectProvider(descriptor, requestingBeanName); } else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName); } else { Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary( descriptor, requestingBeanName); if (result == null) { result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); } return result; } } //根据工厂中定义的bean解析指定的依赖项 public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { // spring第一次创建依赖的时候,会存放在shortcut,后面就不用再解析了 Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } // 获取注入属性的类型 Class<?> type = descriptor.getDependencyType(); // 处理@Value的值 Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { // 解析value if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); try { return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor()); } catch (UnsupportedOperationException ex) { // A custom TypeConverter which does not support TypeDescriptor resolution... return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } } // 对数组容器的处理, Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } // 对非数组、容器对象的处理,键值对 Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { // 为空,且required为true,抛异常 if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; // 有多个的情况,筛选一个 if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { // In case of an optional Collection/Map, silently ignore a non-unique case: // possibly it was meant to be an empty collection of multiple regular beans // (before 4.3 in particular when we didn't even look for collection beans). return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { // We have exactly one match. // 只有一个,直接返回 Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } } //解析数组容器 private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) { final Class<?> type = descriptor.getDependencyType(); if (descriptor instanceof StreamDependencyDescriptor) { Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } Stream<Object> stream = matchingBeans.keySet().stream() .map(name -> descriptor.resolveCandidate(name, type, this)) .filter(bean -> !(bean instanceof NullBean)); if (((StreamDependencyDescriptor) descriptor).isOrdered()) { stream = stream.sorted(adaptOrderComparator(matchingBeans)); } return stream; } else if (type.isArray()) { // 数组的情况 Class<?> componentType = type.getComponentType(); ResolvableType resolvableType = descriptor.getResolvableType(); Class<?> resolvedArrayType = resolvableType.resolve(type); if (resolvedArrayType != type) { componentType = resolvableType.getComponentType().resolve(); } if (componentType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), resolvedArrayType); if (result instanceof Object[]) { Comparator<Object> comparator = adaptDependencyComparator(matchingBeans); if (comparator != null) { Arrays.sort((Object[]) result, comparator); } } return result; } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { // 容器的情况 Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric(); if (elementType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); Object result = converter.convertIfNecessary(matchingBeans.values(), type); if (result instanceof List) { Comparator<Object> comparator = adaptDependencyComparator(matchingBeans); if (comparator != null) { ((List<?>) result).sort(comparator); } } return result; } else if (Map.class == type) { // map的情况 ResolvableType mapType = descriptor.getResolvableType().asMap(); Class<?> keyType = mapType.resolveGeneric(0); if (String.class != keyType) { return null; } Class<?> valueType = mapType.resolveGeneric(1); if (valueType == null) { return null; } Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, new MultiElementDescriptor(descriptor)); if (matchingBeans.isEmpty()) { return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } return matchingBeans; } else { return null; } } //Required是否为true private boolean isRequired(DependencyDescriptor descriptor) { return getAutowireCandidateResolver().isRequired(descriptor); } //注入属性是数组或者容器 private boolean indicatesMultipleBeans(Class<?> type) { return (type.isArray() || (type.isInterface() && (Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)))); } //适配依赖比较器 private Comparator<Object> adaptDependencyComparator(Map<String, ?> matchingBeans) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).withSourceProvider( createFactoryAwareOrderSourceProvider(matchingBeans)); } else { return comparator; } } //比较器 private Comparator<Object> adaptOrderComparator(Map<String, ?> matchingBeans) { Comparator<Object> dependencyComparator = getDependencyComparator(); OrderComparator comparator = (dependencyComparator instanceof OrderComparator ? (OrderComparator) dependencyComparator : OrderComparator.INSTANCE); return comparator.withSourceProvider(createFactoryAwareOrderSourceProvider(matchingBeans)); } //创建工厂获取程序提供者 private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, ?> beans) { IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>(); beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName)); return new FactoryAwareOrderSourceProvider(instancesToBeanNames); } //查找Auto候选人 protected Map<String, Object> findAutowireCandidates( @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) { // 获取批评类型的beanName String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this, requiredType, true, descriptor.isEager()); // 存放结果 Map<String, Object> result = new LinkedHashMap<>(candidateNames.length); // 如果遍历的类型是指定的类型或者子类的话,报错在result for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) { Class<?> autowiringType = classObjectEntry.getKey(); if (autowiringType.isAssignableFrom(requiredType)) { Object autowiringValue = classObjectEntry.getValue(); autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType); if (requiredType.isInstance(autowiringValue)) { result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue); break; } } } for (String candidate : candidateNames) { // 如果不是自引用,且符合注入的条件 if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } // result为空 if (result.isEmpty()) { // 注入属性是数组和容器类型,对泛型检查 boolean multiple = indicatesMultipleBeans(requiredType); // Consider fallback matches if the first pass failed to find anything... DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) && (!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) { addCandidateEntry(result, candidate, descriptor, requiredType); } } // 为空,且不是数组和容器类型,添加自引用 if (result.isEmpty() && !multiple) { // Consider self references as a final pass... // but in the case of a dependency collection, not the very same bean itself. for (String candidate : candidateNames) { if (isSelfReference(beanName, candidate) && (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) && isAutowireCandidate(candidate, fallbackDescriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType); } } } } return result; } //加入到candidate,在主候选项选择之前防止早期的bean初始化。 private void addCandidateEntry(Map<String, Object> candidates, String candidateName, DependencyDescriptor descriptor, Class<?> requiredType) { if (descriptor instanceof MultiElementDescriptor) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); if (!(beanInstance instanceof NullBean)) { candidates.put(candidateName, beanInstance); } } else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor && ((StreamDependencyDescriptor) descriptor).isOrdered())) { Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this); candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance)); } else { candidates.put(candidateName, getType(candidateName)); } } //确定Auto的候选人 protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) { Class<?> requiredType = descriptor.getDependencyType(); // 如果是主要的,直接返回 String primaryCandidate = determinePrimaryCandidate(candidates, requiredType); if (primaryCandidate != null) { return primaryCandidate; } // 如果是最高级的,直接返回 String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType); if (priorityCandidate != null) { return priorityCandidate; } // Fallback // 如果不是主要和最高级的 for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateName = entry.getKey(); Object beanInstance = entry.getValue(); if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) || matchesBeanName(candidateName, descriptor.getDependencyName())) { return candidateName; } } return null; } //判定情况(如果是主要的情况) protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) { String primaryBeanName = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (isPrimary(candidateBeanName, beanInstance)) { if (primaryBeanName != null) { boolean candidateLocal = containsBeanDefinition(candidateBeanName); boolean primaryLocal = containsBeanDefinition(primaryBeanName); if (candidateLocal && primaryLocal) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "more than one 'primary' bean found among candidates: " + candidates.keySet()); } else if (candidateLocal) { primaryBeanName = candidateBeanName; } } else { primaryBeanName = candidateBeanName; } } } return primaryBeanName; } //如果是最高级的情况 protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) { String highestPriorityBeanName = null; Integer highestPriority = null; for (Map.Entry<String, Object> entry : candidates.entrySet()) { String candidateBeanName = entry.getKey(); Object beanInstance = entry.getValue(); if (beanInstance != null) { Integer candidatePriority = getPriority(beanInstance); if (candidatePriority != null) { if (highestPriorityBeanName != null) { if (candidatePriority.equals(highestPriority)) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), "Multiple beans found with the same priority ('" + highestPriority + "') among candidates: " + candidates.keySet()); } else if (candidatePriority < highestPriority) { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } else { highestPriorityBeanName = candidateBeanName; highestPriority = candidatePriority; } } } } return highestPriorityBeanName; } //是否为主要的,即有primary protected boolean isPrimary(String beanName, Object beanInstance) { if (containsBeanDefinition(beanName)) { return getMergedLocalBeanDefinition(beanName).isPrimary(); } BeanFactory parent = getParentBeanFactory(); return (parent instanceof DefaultListableBeanFactory && ((DefaultListableBeanFactory) parent).isPrimary(beanName, beanInstance)); } //获取优先级 protected Integer getPriority(Object beanInstance) { Comparator<Object> comparator = getDependencyComparator(); if (comparator instanceof OrderComparator) { return ((OrderComparator) comparator).getPriority(beanInstance); } return null; } //确定给定的候选名称是否与bean名或别名匹配存储在这个bean定义中 protected boolean matchesBeanName(String beanName, @Nullable String candidateName) { return (candidateName != null && (candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName))); } //是否自引用 private boolean isSelfReference(@Nullable String beanName, @Nullable String candidateName) { return (beanName != null && candidateName != null && (beanName.equals(candidateName) || (containsBeanDefinition(candidateName) && beanName.equals(getMergedLocalBeanDefinition(candidateName).getFactoryBeanName())))); } //没有匹配,抛异常 private void raiseNoMatchingBeanFound( Class<?> type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException { checkBeanNotOfRequiredType(type, descriptor); throw new NoSuchBeanDefinitionException(resolvableType, "expected at least 1 bean which qualifies as autowire candidate. " + "Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations())); } //检查 private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) { for (String beanName : this.beanDefinitionNames) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); Class<?> targetType = mbd.getTargetType(); // 指定的的类型是mbd的targetType子类且符合自动注入条件 if (targetType != null && type.isAssignableFrom(targetType) && isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) { // Probably a proxy interfering with target type match -> throw meaningful exception. Object beanInstance = getSingleton(beanName, false); // 获取bean的类型 Class<?> beanType = (beanInstance != null && beanInstance.getClass() != NullBean.class ? beanInstance.getClass() : predictBeanType(beanName, mbd)); // 实际类型不是指定类型的子类 if (beanType != null && !type.isAssignableFrom(beanType)) { throw new BeanNotOfRequiredTypeException(beanName, type, beanType); } } } // 从父类检查 BeanFactory parent = getParentBeanFactory(); if (parent instanceof DefaultListableBeanFactory) { ((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor); } } //创建一个Optional的依赖 private Optional<?> createOptionalDependency( DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) { DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) { @Override public boolean isRequired() { return false; } @Override public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, args) : super.resolveCandidate(beanName, requiredType, beanFactory)); } }; Object result = doResolveDependency(descriptorToUse, beanName, null, null); return (result instanceof Optional ? (Optional<?>) result : Optional.ofNullable(result)); } //重写toString方法 public String toString() { StringBuilder sb = new StringBuilder(ObjectUtils.identityToString(this)); sb.append(": defining beans ["); sb.append(StringUtils.collectionToCommaDelimitedString(this.beanDefinitionNames)); sb.append("]; "); BeanFactory parent = getParentBeanFactory(); if (parent == null) { sb.append("root of factory hierarchy"); } else { sb.append("parent: ").append(ObjectUtils.identityToString(parent)); } return sb.toString(); }
- 面向用户的高级容器——ApplicationContext接口体系
ApplicationContext直接翻译也被称作应用上下文,其实这个字面很难被理解,Context的意思是上下文、环境,其实个人认为翻译成应用环境可能会更好一些,可以认为ApplicationContext是一种定义了维护BeanDefinition和实例化对象之间协作关系的高级接口,而这个高级接口,又是利用了Spring中普通容器来实现的,所以也被称作高级容器,也是我们平时认为的Spring容器体系,因为BeanFactroy虽然也是容器,但是平时我们直接接触不到,作为用户,平时在使用的时候,我们直接用的是ApplicationContext高级容器,也就是说,高级容器是面向用户的,而普通容器是面向框架的,是Spring容器的基石。
ApplicationContext接口继承自BeanFactory的二级接口ListableBeanFactory和HierarchicalBeanFactroy。所以高级容器其实也是在普通容器的基础上实现的,在普通容器的基础上扩展除了非常丰富的功能接口来供用户使用,如果深入去阅读源码,会发现其实在高级容器的一个很重要的抽象类AbstractRefreshableApplicationContext内部,是有一个私有的普通容器对象的,而我们常用的一些高级容器实现类,比如FileSystemXmlApplicationContext、AnnotatioConfigWebApplicationContext等都继承自这个抽象类,也就是说都继承了这个普通容器对象:
这个内部的DefaultListableBeanFactory
对象,通常也被称作内部容器,Spring的设计大量运用了委托模式的思想,这里在高级容器内部实例化一个内部容器出来,将普通容器的所有操作都委托给内部容器去实现,而高级容器本身只需要关注与拓展面向用户的操作即可。
下图是ApplicationContext
体系类图,之后我们将展开分析一下这个体系:
高级容器的顶级接口——ApplicationContext接口
首先,ApplicationContext接口继承自ListableBeanFactory和HierarchicalBeanFactroy,也就是ApplicationContext下面的接口和类,都继承或者实现了BeanFactroy体系中的大部分功能,包括对BeanDefinition的单个与批量操作和容器分层的方法。在此基础上,ApplicationContext还同时继承了其它四个接口,对容器进行了方法的扩展 - AbstractAutowireCapableBeanFactory主要是用于自动装配,Bean的创建、属性填充、连接(包括自动装配)、初始化和销毁,以及BeanPostProcessor的调用。
spring学习之源码分析--AbstractAutowireCapableBeanFactory - SegmentFault 思否
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。