共计 89786 个字符,预计需要花费 225 分钟才能阅读完成。
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,一个为 SingletonBeanRegistry-
ConfigurableBeanFactory 接口源码 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 思否