Spring 5 AbstractAutowireCapableBeanFactory 源码注释

tech2022-10-02  114

相关源码注释

Spring 5 SimpleAliasRegistry 源码注释 Spring 5 DefaultSingletonBeanRegistry 源码注释 Spring 5 FactoryBeanRegistrySupport 源码注释 Spring 5 AbstractBeanFactory 源码注释 Spring 5 AbstractAutowireCapableBeanFactory 源码注释 Spring 5 DefaultLisbaleBeanFactory 源码注释

UML类图

源码

/** * Abstract bean factory superclass that implements default bean creation, * with the full capabilities specified by the {@link RootBeanDefinition} class. * Implements the {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory} * interface in addition to AbstractBeanFactory's {@link #createBean} method. * <p>实现缺省bean创建的抽象bean工厂超类,具有由RootBeanDefinition类指定的全部功能. * 除了AbstractBeanFactory的createBean方法之外,还实现了AutowireCapableBeanFactory接口.</p> * * <p>Provides bean creation (with constructor resolution), property population, * wiring (including autowiring), and initialization. Handles runtime bean * references, resolves managed collections, calls initialization methods, etc. * Supports autowiring constructors, properties by name, and properties by type. * <p>提供bean创建(带有构造函数解析)、属性填充、连接(包括自动装配)和初始化。处理运行时bean引用、 * 解析托管集合、调用初始化方法等。支持自动装配构造函数,按名称和按类型的属性。</p> * * <p>The main template method to be implemented by subclasses is * {@link #resolveDependency(DependencyDescriptor, String, Set, TypeConverter)}, * used for autowiring by type. In case of a factory which is capable of searching * its bean definitions, matching beans will typically be implemented through such * a search. For other factory styles, simplified matching algorithms can be implemented. * <p>由子类实现的主要模板方法是resolveDependency(DependencyDescriptor, String, Set, TypeConverter), * 用于按类型自动装配。对于能够搜索其beanDefinition的工厂,匹配bean通常是通过这样的搜索实现的。对于其他工厂样式, * 可以实现简化的匹配算法。</p> * * <p>Note that this class does <i>not</i> assume or implement bean definition * registry capabilities. See {@link DefaultListableBeanFactory} for an implementation * of the {@link org.springframework.beans.factory.ListableBeanFactory} and * {@link BeanDefinitionRegistry} interfaces, which represent the API and SPI * view of such a factory, respectively. * <p>注意,这个类没有假设或实现bean定义注册表功能.有关org.springframework.beans.factory.ListableBeanFactory * 和 BeanDefinitionRegistry 的实现请查阅DefaultListableBeanFactory,分别表示此类工厂的API和SPI视图。</p> * obtainFromSupplier * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @author Mark Fisher * @author Costin Leau * @author Chris Beams * @author Sam Brannen * @author Phillip Webb * @since 13.02.2004 * @see RootBeanDefinition * @see DefaultListableBeanFactory * @see BeanDefinitionRegistry */ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { /** * Strategy for creating bean instances. * 创建Bean实例的策略 * */ private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy(); /** * Resolver strategy for method parameter names. * <p>方法参数的解析策略</p> * */ @Nullable private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); /** * Whether to automatically try to resolve circular references between beans. * <p>是否尝试自动解决Bean之间的循环引用。</p> * <p>循环引用的意思是:A引用了B,B引用了C,C又引用了A</p> * */ private boolean allowCircularReferences = true; /** * Whether to resort to injecting a raw bean instance in case of circular reference, * even if the injected bean eventually got wrapped. * <p>在循环引用的情况下,是否借助于注入原始Bean实例,即使注入的Bean最终被包装</p> */ private boolean allowRawInjectionDespiteWrapping = false; /** * Dependency types to ignore on dependency check and autowire, as Set of * Class objects: for example, String. Default is none. * <p>依赖项检查和自动装配时要忽略的依赖类型,如一组 class 对象;例如,String.默认时没有的</p> */ private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>(); /** * Dependency interfaces to ignore on dependency check and autowire, as Set of * Class objects. By default, only the BeanFactory interface is ignored. * <p>依赖接口忽略依赖检查和自动装配,作为类对象的集合。默认情况下,仅BeanFactory * 接口被湖绿</p> */ private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>(); /** * The name of the currently created bean, for implicit dependency registration * on getBean etc invocations triggered from a user-specified Supplier callback. * <p>当前创建的bean名称,用于从用户指定的Supplier回调触发的对getBean等调用的隐式依赖项注册</p> */ private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean"); /** * Cache of unfinished FactoryBean instances: FactoryBean name to BeanWrapper. * <p>未完成的FactoryBean实例的高速缓存:FactoryBean名-BeanWrapper</p> * */ private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>(); /** * Cache of candidate factory methods per factory class. * <p>每个工厂类的缓存候选工厂方法</p> * */ private final ConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>(); /** * Cache of filtered PropertyDescriptors: bean Class to PropertyDescriptor array. * <p>过滤后的PropertyDescriptor的缓存:bean类到PropertyDescriptors数组</p> * */ private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache = new ConcurrentHashMap<>(); /** * Create a new AbstractAutowireCapableBeanFactory. * <p>创建一个新的AbstractAutowireCapableBeanFactory </p> */ public AbstractAutowireCapableBeanFactory() { //父级AbstractorBeanFactory是个空实现方法 super(); //将BeanNameAware 添加到 忽略依赖类对象集合中 ignoreDependencyInterface(BeanNameAware.class); //将BeanFactoryAware 添加到 忽略依赖类对象集合中 ignoreDependencyInterface(BeanFactoryAware.class); //将BeanClassLoaderAware 添加到 忽略依赖类对象集合中 ignoreDependencyInterface(BeanClassLoaderAware.class); } /** * Create a new AbstractAutowireCapableBeanFactory with the given parent. * <p>使用给定的父级Bean工厂创建一个新的AbstractAutowireCapableBeanFactory</p> * @param parentBeanFactory parent bean factory, or {@code null} if none * -- 父级bean工厂,如果没有可以为{@code null} */ public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) { this(); //设置此bean工厂的父级,如果此工厂有父级bean工厂了会抛出IllegalStateException setParentBeanFactory(parentBeanFactory); } /** * Set the instantiation strategy to use for creating bean instances. * Default is CglibSubclassingInstantiationStrategy. * @see CglibSubclassingInstantiationStrategy */ public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) { this.instantiationStrategy = instantiationStrategy; } /** * Return the instantiation strategy to use for creating bean instances. * <p>返回用于创建Bean实例的实例化策略</p> */ protected InstantiationStrategy getInstantiationStrategy() { return this.instantiationStrategy; } /** * Set the ParameterNameDiscoverer to use for resolving method parameter * names if needed (e.g. for constructor names). * <p>Default is a {@link DefaultParameterNameDiscoverer}. */ public void setParameterNameDiscoverer(@Nullable ParameterNameDiscoverer parameterNameDiscoverer) { this.parameterNameDiscoverer = parameterNameDiscoverer; } /** * Return the ParameterNameDiscoverer to use for resolving method parameter * names if needed. * <p>如果需要,返回ParameterNameDiscover来解析方法参数名称</p> */ @Nullable protected ParameterNameDiscoverer getParameterNameDiscoverer() { return this.parameterNameDiscoverer; } /** * Set whether to allow circular references between beans - and automatically * try to resolve them. * <p>设置是否在bean之间允许循环引用-并自动尝试解决它们</p> * * <p>Note that circular reference resolution means that one of the involved beans * will receive a reference to another bean that is not fully initialized yet. * This can lead to subtle and not-so-subtle side effects on initialization; * it does work fine for many scenarios, though. * <p>注意,循环引用解析意味着其中一个涉及的bean将收到对另一个尚未完全初始化的bean引用。 * 者可能会导致初始化方面。这可能会导致初始化方面的细微和不太细微的副作用;不过,它在 * 许多情况下都可以正常工厂。</p> * * <p>Default is "true". Turn this off to throw an exception when encountering * a circular reference, disallowing them completely. * <p>默认值为true,遇到循环引用是,请关闭此选项以引发异常,从而完全禁止它们。</p> * * <p><b>NOTE:</b> It is generally recommended to not rely on circular references * between your beans. Refactor your application logic to have the two beans * involved delegate to a third bean that encapsulates their common logic. * <p>注意:通常建议不要在bean之间循环引用。重构您的应用程序逻辑,以使涉及的两个bean * 委托给封装了它们公共逻辑的第三bean</p> * <p>循环引用的意思是:A引用了B,B引用了C,C又引用了A</p> */ public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; } /** * Set whether to allow the raw injection of a bean instance into some other * bean's property, despite the injected bean eventually getting wrapped * (for example, through AOP auto-proxying). * <p>设置是否允许将一个Bean实例原始注入到其他Bean的属性中,尽管注入的Bean最终被包装 * (例如,通过AOP自动代理)</p> * <p>This will only be used as a last resort in case of a circular reference * that cannot be resolved otherwise: essentially, preferring a raw instance * getting injected over a failure of the entire bean wiring process. * <p>这只会循环引用无法通过其他方式解决的情况下作为最后的手段使用:本质上,在整个 * bean连接过程失败的情况下,宁愿注入一个原始实例</p> * <p>Default is "false", as of Spring 2.0. Turn this on to allow for non-wrapped * raw beans injected into some of your references, which was Spring 1.2's * (arguably unclean) default behavior. * <p>从Spring2.0开始,默认值是false。打开这个选项,允许将未包装的原始Bean注入到一些引用 * 中,这是Spring1.2的默认行为(可以说是不干净)</p> * <p><b>NOTE:</b> It is generally recommended to not rely on circular references * between your beans, in particular with auto-proxying involved. * <p>注意:通常建议不要依赖与Bean之间的循环引用,特别是涉及到自动代理时。</p> * @see #setAllowCircularReferences */ public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) { this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping; } /** * Ignore the given dependency type for autowiring: * for example, String. Default is none. */ public void ignoreDependencyType(Class<?> type) { this.ignoredDependencyTypes.add(type); } /** * Ignore the given dependency interface for autowiring. * <p>忽略给定的依赖接口进行自动装配</p> * * <p>This will typically be used by application contexts to register * dependencies that are resolved in other ways, like BeanFactory through * BeanFactoryAware or ApplicationContext through ApplicationContextAware. * <p>应用程序上下文通常会使用它来注册依赖关系解决其他方式,例如BeanFactory通 * 过BeanFactoryAware或者ApplicationContext通过ApplicationContextAware注册</p> * * <p>By default, only the BeanFactoryAware interface is ignored. * For further types to ignore, invoke this method for each type. * <p>默认情况下,仅BeanFactoryAware接口被忽略。要忽略其他类型,请忽略其他类型,请 * 为每钟类型调用此方法。</p> * * @see org.springframework.beans.factory.BeanFactoryAware * @see org.springframework.context.ApplicationContextAware */ public void ignoreDependencyInterface(Class<?> ifc) { //将要忽略的类添加到 忽略依赖类对象集合中 this.ignoredDependencyInterfaces.add(ifc); } @Override public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) { super.copyConfigurationFrom(otherFactory); if (otherFactory instanceof AbstractAutowireCapableBeanFactory) { AbstractAutowireCapableBeanFactory otherAutowireFactory = (AbstractAutowireCapableBeanFactory) otherFactory; this.instantiationStrategy = otherAutowireFactory.instantiationStrategy; this.allowCircularReferences = otherAutowireFactory.allowCircularReferences; this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes); this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces); } } //------------------------------------------------------------------------- // Typical methods for creating and populating external bean instances //------------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public <T> T createBean(Class<T> beanClass) throws BeansException { // Use prototype bean definition, to avoid registering bean as dependent bean. RootBeanDefinition bd = new RootBeanDefinition(beanClass); bd.setScope(SCOPE_PROTOTYPE); bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader()); return (T) createBean(beanClass.getName(), bd, null); } @Override public void autowireBean(Object existingBean) { // Use non-singleton bean definition, to avoid registering bean as dependent bean. RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean)); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader()); BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); populateBean(bd.getBeanClass().getName(), bd, bw); } @Override public Object configureBean(Object existingBean, String beanName) throws BeansException { markBeanAsCreated(beanName); BeanDefinition mbd = getMergedBeanDefinition(beanName); RootBeanDefinition bd = null; if (mbd instanceof RootBeanDefinition) { RootBeanDefinition rbd = (RootBeanDefinition) mbd; bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition()); } if (bd == null) { bd = new RootBeanDefinition(mbd); } if (!bd.isPrototype()) { bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader()); } BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); populateBean(beanName, bd, bw); return initializeBean(beanName, existingBean, bd); } //------------------------------------------------------------------------- // Specialized methods for fine-grained control over the bean lifecycle //------------------------------------------------------------------------- @Override public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { // Use non-singleton bean definition, to avoid registering bean as dependent bean. RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); return createBean(beanClass.getName(), bd, null); } @Override public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException { // Use non-singleton bean definition, to avoid registering bean as dependent bean. final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) { return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance(); } else { Object bean; final BeanFactory parent = this; if (System.getSecurityManager() != null) { bean = AccessController.doPrivileged((PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(bd, null, parent), getAccessControlContext()); } else { bean = getInstantiationStrategy().instantiate(bd, null, parent); } populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean)); return bean; } } @Override public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException { if (autowireMode == AUTOWIRE_CONSTRUCTOR) { throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance"); } // Use non-singleton bean definition, to avoid registering bean as dependent bean. RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); populateBean(bd.getBeanClass().getName(), bd, bw); } @Override public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException { markBeanAsCreated(beanName); BeanDefinition bd = getMergedBeanDefinition(beanName); BeanWrapper bw = new BeanWrapperImpl(existingBean); initBeanWrapper(bw); applyPropertyValues(beanName, bd, bw, bd.getPropertyValues()); } @Override public Object initializeBean(Object existingBean, String beanName) { return initializeBean(beanName, existingBean, null); } @Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { //初始化返回结果为existingBean Object result = existingBean; //遍历 该工厂创建的bean的BeanPostProcessors列表 for (BeanPostProcessor processor : getBeanPostProcessors()) { //postProcessBeforeInitialization:在任何Bean初始化回调之前(如初始化Bean的afterPropertiesSet或自定义的init方法) // 将此BeanPostProcessor 应用到给定的新Bean实例。Bean已经填充了属性值。返回的Bean实例可能时原始Bean的包装器。 // 默认实现按原样返回给定的 Bean Object current = processor.postProcessBeforeInitialization(result, beanName); // 如果 current为null if (current == null) { //直接返回result,中断其后续的BeanPostProcessor处理 return result; } //让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装 result = current; } //返回经过所有BeanPostProcess对象的后置处理的层层包装后的result return result; } /** * 对 existingBean 进行初始化后的后处理: * <ol> * <li>初始化结果对象为result,默认引用existingBean</li> * <li>遍历该工厂创建的bean的BeanPostProcessors列表: * <ol> * <li>回调BeanPostProcessor#postProcessAfterInitialization来对result进行包装【变量 current】</li> * <li>如果current为null,直接返回result,中断其后续的BeanPostProcessor处理</li> * <li>让result引用current,使其经过所有BeanPostProcess对象的后置处理的层层包装</li> * </ol> * </li> * <li>返回经过所有BeanPostProcess对象的后置处理的层层包装后的result</li> * </ol> * @param existingBean the existing bean instance -- 现有的bean实例 * @param beanName the name of the bean, to be passed to it if necessary * (only passed to {@link BeanPostProcessor BeanPostProcessors}; * can follow the {@link #ORIGINAL_INSTANCE_SUFFIX} convention in order to * enforce the given instance to be returned, i.e. no proxies etc) * Bean名称,必要时将传递给它(仅传递给BeanPostProcessor;可以遵循ORIGINAL_INSTANCE_SUFFIX * 约定以强制返回给定的实例,即没有代理等) * @return * @throws BeansException */ @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { //初始化结果对象为result,默认引用existingBean Object result = existingBean; //遍历该工厂创建的bean的BeanPostProcessors列表 for (BeanPostProcessor processor : getBeanPostProcessors()) { //回调BeanPostProcessor#postProcessAfterInitialization来对现有的bean实例进行包装 Object current = processor.postProcessAfterInitialization(result, beanName); //一般processor对不感兴趣的bean会回调直接返回result,使其能继续回调后续的BeanPostProcessor; // 但有些processor会返回null来中断其后续的BeanPostProcessor //如果current为null if (current == null) { //直接返回result,中断其后续的BeanPostProcessor处理 return result; } //让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装 result = current; } //返回经过所有BeanPostProcess对象的后置处理的层层包装后的result return result; } @Override public void destroyBean(Object existingBean) { new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy(); } //------------------------------------------------------------------------- // Delegate methods for resolving injection points //------------------------------------------------------------------------- @Override public Object resolveBeanByName(String name, DependencyDescriptor descriptor) { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); try { return getBean(name, descriptor.getDependencyType()); } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } } @Override @Nullable public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException { return resolveDependency(descriptor, requestingBeanName, null, null); } //--------------------------------------------------------------------- // Implementation of relevant AbstractBeanFactory template methods //--------------------------------------------------------------------- /** * Central method of this class: creates a bean instance, * populates the bean instance, applies post-processors, etc. * <p>此类的重要方法:创建Bean实例,填充Bean实例,应用后处理器等</p> * @see #doCreateBean */ @Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { //如果开启跟踪级别日志 if (logger.isTraceEnabled()) { //打印跟踪日志 : 创建bean的实例'beanName' logger.trace("Creating instance of bean '" + beanName + "'"); } //mbd的深度副本 RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 确保此时确实解析了bean类,并在无法动态存储的Class不能存储在共享合并后 // BeanDefinition中的情况下克隆beanDefinition //为mdb解析出对应的bean class Class<?> resolvedClass = resolveBeanClass(mbd, beanName); //如果成功解析出Class 且 mbd没有指定了bean类 且 mbd配置了bean类名 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { //创建一个新的RootBeanDefinition作为mbd的深层副本 mbdToUse = new RootBeanDefinition(mbd); //将解析出来的reolvedClass设置到mbd副本里 mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. // 准备方法替代 try { //验证并准备mbdToUse的方法替换。检查是否存在具有指定名称的方法。 mbdToUse.prepareMethodOverrides(); } //捕捉BeanDefinition验证失败时引发的异常 catch (BeanDefinitionValidationException ex) { //Bean定义存储异常:beanName,验证失败 throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. // 给BeanPostProcessors一个返回代理而不是目标bean实例的机会 //应用InstantiationAwareBeanPostProcessor后处理器实例化benName的实例对象 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); //如果成功获取到了实例对象 if (bean != null) { //直接返回这个实例对象 return bean; } } catch (Throwable ex) { //抛出Bean创建异常:Bean实例化之前的BeanPostProcess失败 throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { //实际创建Bean的方法 Object beanInstance = doCreateBean(beanName, mbdToUse, args); //如果日志级别是跟踪 if (logger.isTraceEnabled()) { //打印跟踪日志:完成创建Bean的创建 logger.trace("Finished creating instance of bean '" + beanName + "'"); } //返回bean实例 return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {//捕捉Bean创建异常|隐式出现的单例异常 // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. // 之前检测到的异常已经带有正确的bean创建上下文,或者非法的单例状态要传递给 DefaultSingletonBeanRegistry //重新抛出ex throw ex; } catch (Throwable ex) {//捕捉创建Bean出现的所有异常 //抛出Bean创建异常:创建Bean期间的意外异常 throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } } /** * <p>实际创建指定的bean: * <ol> * <li>使用适当的实例化策略为指定的Bean创建一个新实例:工厂方法,构造函数自动装配或简单实例化。</li> * <li>将 工厂中的所有 MergedBeanDefinitionPostProcessors 应用到mbd ,调用这些后处理器 的 postProcessMergedBeanDefinition 方法</li> * <li>用来自 BeanDefinition的属性值填充instanceWrapper中的bean实例</li> * <li>初始化给定的Bean实例,应用工厂回调以及init方法和BeanPostProcessors</li> * <li>将bean添加到该工厂中的可丢弃Bean列表中,注册器可丢弃Bean接口 和/或 在工厂关闭 时调用给</li> * </ol> * </p> * Actually create the specified bean. Pre-creation processing has already happened * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks. * <p>实际创建指定的bean。此时,预创建处理已经发生,例如检查postProcessBeforeInstantiation回调。</p> * <p>Differentiates between default bean instantiation, use of a * factory method, and autowiring a constructor. * <p>在默认bean实例化,使用工厂方法和自动装配构造函数之间进行区分</p> * @param beanName the name of the bean --bean名 * @param mbd the merged bean definition for the bean -- 合并后的beanDefinition * @param args explicit arguments to use for constructor or factory method invocation * -- 用于构造函数或工厂方法调用的显示参数 * @return a new instance of the bean -- bean新实例 * @throws BeanCreationException if the bean could not be created -- 如果无法创建bean * @see #instantiateBean * @see #instantiateUsingFactoryMethod * @see #autowireConstructor */ protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. //实例化bean //BeanWrapper是对Bean的包装,其接口中所定义的功能很简单包括设置获取被包装的对象, // 获取被包装bean的属性描述器,由于BeanWrapper接口是PropertyAccessor的子接口, // 因此其也可以设置以及访问被包装对象的属性值。BeanWrapper大部分情况下是在spring ioc // 内部进行使用, 通过BeanWrapper,spring ioc容器可以用统一的方式来访问bean的属性。 // 用户很少需要直接使用 BeanWrapper进行编程。 // 实例bean的包装对象 BeanWrapper instanceWrapper = null; //如果mbd配置的时单例作用域 if (mbd.isSingleton()) { //从未完成的FactoryBean实例的高速缓存中移除beanName的BeanWrapper instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } //如果包装对象获取失败 if (instanceWrapper == null) { //使用适当的实例化策略为指定的Bean创建一个新实例:工厂方法,构造函数自动装配或简单实例化。 instanceWrapper = createBeanInstance(beanName, mbd, args); } //获取 instanceWrapperd包装的bean实例 final Object bean = instanceWrapper.getWrappedInstance(); //获取 instanceWrapperd包装的bean类型 Class<?> beanType = instanceWrapper.getWrappedClass(); //如果beanType不是NullBean if (beanType != NullBean.class) { //将beanType 缓存到 mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. // 允许后处理程序修改合并后的BeanDefinition // 使用mbd的后处理器通用锁保证线程安全 synchronized (mbd.postProcessingLock) { //如果mdb没有应用过MergedBeanDefinitionPostProcessor if (!mbd.postProcessed) { try { //将 工厂中的所有 MergedBeanDefinitionPostProcessors 应用到mbd ,调用这些后处理器 的 postProcessMergedBeanDefinition 方法 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { //捕捉 工厂中的所有 MergedBeanDefinitionPostProcessors应用mbd时的抛出的所有异常,重写抛出Bean创建异常 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } //标记该mbd已经应用过 工厂中的所有 MergedBeanDefinitionPostProcessors mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 饿汉式缓存 单例能够解决 循环依赖,即使被生命周期接口触发。 // 单例饿汉式暴露的情况标记 = 如果mdb的Bean对象是单例 且 允许自动解决循环依赖问题 且 该beanName正在创建(在整个工厂内) boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); //如果是单例饿汉式暴露的情况 if (earlySingletonExposure) { //打印跟踪信息 if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } //添加 新的单例对象工厂 来构建 指定的单例对象。 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. // 初始化Bean实例 //初始化暴露对象为bean Object exposedObject = bean; try { //用来自 BeanDefinition的属性值填充instanceWrapper中的bean实例 populateBean(beanName, mbd, instanceWrapper); //初始化给定的Bean实例,应用工厂回调以及init方法和BeanPostProcessors exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) {//捕捉赋值属性,初始化Bean时抛出的任何异常 //如果ex是属于Bean创建异常 && bean名与ex的异常Bean名一致 if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { //重新ex throw (BeanCreationException) ex; } else { //抛出Bean创建异常:bean的初始化失败 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } //如果是单例饿汉式暴露的情况 if (earlySingletonExposure) { //获取获取以beanName注册的(原始)单例对象,不允许创建早期引用 Object earlySingletonReference = getSingleton(beanName, false); //earlySingletonReference不为null if (earlySingletonReference != null) { //如果exposedObject与bean是同一个对象 if (exposedObject == bean) { //exposedObject就为 earlySingletonReference exposedObject = earlySingletonReference; } //如果 在循环引用的情况下,不借助注入原始Bean实例,即使注入的Bean最终被包装 && 已经为beanName注册了依赖Bean关系 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { //获取依赖于beanName的所有Bean名称 String[] dependentBeans = getDependentBeans(beanName); //定义实际的Bean依赖Set集合,长度与dependentBeans保持一致 Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); //遍历dependentBeans for (String dependentBean : dependentBeans) { //removeSingletonIfCreatedForTypeCheckOnly:删除给定Bean名称的单例实例(如果有的话),但仅当它没有用于类型检查之外的其他目的时才删除 //如果没能删除dependentBean if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { //将dependentBean添加到 actualDependentBeans actualDependentBeans.add(dependentBean); } } //如果actualDependentBeans不为空 if (!actualDependentBeans.isEmpty()) { //抛出Bean当前在创建中异常:名为'BeanName'的Bean在其原始版本中作为循环引用的一部分被注入到其他Bean[actualDependentBeans]中,但 // 最终被包装了。这意味着其他Bean不适用Bean的最终版本。这通常时过度渴望类型匹配的结果-例如,考虑在关闭'allowEagerInit'标志的 // 情况下使用'getBeanNamesOfType' throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. // 将Bean一次性注册了 try { //将bean添加到该工厂中的可丢弃Bean列表中,注册器可丢弃Bean接口 和/或 在工厂关闭 时调用给 // 定销毁方法(如果适用)。只适用单例 registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { //捕捉 BeanDefinition定义验证异常:无效销毁方法 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } //返回最终要暴露出去的对象 return exposedObject; } /** * <p>预测指定beanName,mbd所提供的信息的最终bean类型 * <ol> * <li>获取mbd的目标类型,赋值给【targetType】</li> * <li>如果mbd的目标类型不为null 且 mbd是由应用程序本身定义的 且 该工厂有InstiationAwareBeanPostProcessor * (一般情况下工厂都会有InstiationAwareBeanPostProcessor): * <ol> * <li>根据typesToMatch构建要匹配的类型只有Factorybean标记</li> * <li>遍历该工厂创建的bean的BeanPostProcessors列表,元素有bp: * <ol> * <li>将bp强转成SmartInstantiationAwareBeanPostProcessor对象【变量bp】</li> * <li>调用ibp的predictBeanType(targetType, beanName)方法获取预测的最终类型【变量 predicted】</li> * <li>如果predicated不为null 且 (typesToMatch构建要匹配的类型不只有Factorybean 或者 predicted属于FactoryBean,就返回predicated</li> * </ol> * </li> * </ol> * </li> * </ol> * </p> * @param beanName the name of the bean -- bean名 * @param mbd the merged bean definition to determine the type for * -- 合并的bean定义以确定其类型 * @param typesToMatch the types to match in case of internal type matching purposes * (also signals that the returned {@code Class} will never be exposed to application code) * -- 内部类型培评时要匹配的类型(也表示返回的Class永远不会保留应用程序代码) * @return */ @Override @Nullable protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { //获取mbd的目标类型 Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch); // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. // 应用SmartInstantiationAwareBeanPostProcessors来预测实例化快捷方式后的最终类型 // 如果mbd的目标类型不为null 且 mbd是由应用程序本身定义的 且 该工厂有InstiationAwareBeanPostProcessor if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //根据typesToMatch构建要匹配的类型只有Factorybean标记 boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class; //遍历该工厂创建的bean的BeanPostProcessors列表 for (BeanPostProcessor bp : getBeanPostProcessors()) { //SmartInstantionAwareBeanPostProcessor:扩展InstantiationAwareBeanPostProcessor接口,添加了用于预测已处理bean的 // 最终类型的回调 //如果bp是SmartInstantiationAwareBeanPostProcessor的实例 if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { //将bp强转成SmartInstantiationAwareBeanPostProcessor对象 SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; //从ibp中获取其最终bean类型 Class<?> predicted = ibp.predictBeanType(targetType, beanName); //如果predicated不为null 且 (typesToMatch构建要匹配的类型不只有Factorybean 或者 predicted属于FactoryBean if (predicted != null && (!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) { return predicted; } } } } return targetType; } /** * <p>确定给定的bean定义的目标类型: * <ol> * <li>从mbd中获取目标类型【targetType】,获取成功就返回</li> * <li>如果bean的合并定义中有设置工厂方法名,就通过工厂方法区解析出targetType</li> * <li>否则调用resolveBeanClass(mbd, beanName, typesToMatch))解析出targetType</li> * <li>如果typeToMatch为空数组 或者 该工厂没有临时类加载器,缓存解析出来的targetType到mbd中,以免重新解析.</li> * <li>返回targetType</li> * </ol> * </p> * Determine the target type for the given bean definition. * <p>确定给定的bean定义的目标类型</p> * @param beanName the name of the bean (for error handling purposes) -- bean名(用于错误处理) * @param mbd the merged bean definition for the bean -- bean的合并bean定义 * @param typesToMatch the types to match in case of internal type matching purposes * (also signals that the returned {@code Class} will never be exposed to application code) * -- 如果要进行内部类型匹配,则要进行匹配(也表明返回Class永远不会暴露给应用程序代码) * @return the type for the bean if determinable, or {@code null} otherwise * -- Bean的类型(如果可以确定的话),否则为 null */ @Nullable protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { //获取bean的合并定义的目标类型 Class<?> targetType = mbd.getTargetType(); //如果没有成功获取到目标类型 if (targetType == null) { //如果bean的合并定义中有设置工厂方法名,就通过工厂方法区解析出targetType,否则 //交给resolveBeanClass方法解析出targetType targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) : resolveBeanClass(mbd, beanName, typesToMatch)); //如果typeToMatch为空数组 或者 该工厂没有临时类加载器 if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) { //缓存解析出来的targetType到mbd中,以免重新解析 mbd.resolvedTargetType = targetType; } } return targetType; } /** * <p>从工厂方法确定给定bean定义的目标类型,仅在尚未为目标bean注册单例实例时调用: * <ol> * <li>获取mbd的工厂方法返回类型【RootBeanDefinition#factoryMethodReturnType】,获取成功就返回出去</li> * <li>定一个通用返回类型【变量commonType】,用于存储 经过比较 AutowireUtils#resolveReturnTypeForFactoryMethod方法的返回结果 * 和Method#getReturnType方法的返回结果所得到共同父类。下面步骤都是为了获取commonType所实施的。</li> * <li>尝试获取bean的合并bean定义中的缓存用于自省的唯一工厂方法对象【RootBeanDefinition#factoryMethodToIntrospect】 * 【变量uniqueCandidate】,没成功获取到uniqueCandidate就通过下面步骤获取: * <ol> * <li>定义一个mbd指定的工厂类【变量factoryClass】</li> * <li>定义一个表明uniqueCandidate是否是静态方法的标记,默认是true【变量isStatic】</li> * <li>获取mbd的FactoryBean名【变量factoryBeanName】 * <ol> * <li>如果获取成功,就意味着需要得到factoryBeanName所指的实例对象才能调用uniqueCandidate, * 即uniqueCandidate不是静态方法: * <ol> * <li>如果factoryBeanName与beanName相等,会抛出BeanDefinitionStoreException,表明FactoryBean引用指向 * 相同的BeanDefinition</li> * <li>调用getType(factoryBeanName)获取其对应的类型【变量factoryClass】</li> * <li>isStatic设置为false,表示uniqueCandidate不是静态方法</li> * </ol> * </li> * <li>否则,调用resolveBeanClass(mbd, beanName, typesToMatch)来得到factoryClass</li> * </ol> * </li> * <li>如果经过上面步骤,factoryClass还是没有成功获取就返回null,表示找到不明确的返回类型</li> * <li>如果mbd有配置构造函数参数值,就获取该构造函数参数值的数量,否则为0【变量 minNrOfArgs】</li> * <li>从该工厂的缓存候选工厂方法集合【factoryMethodCandidateCache】中获取候选方法,如果没有就调用 * ReflectionUtils.getUniqueDeclaredMethods(factoryClass, ReflectionUtils.USER_DECLARED_METHODS))来 * 获取并添加到factoryMethodCandidateCache中【变量 candidates】 * </li> * <li>遍历candidates,元素为candidate.当candidate是否静态的判断结果与isStatic一致 且 candidate有资格作为工厂方法 * 且candidate的方法参数数量>=minNrOfArgs时: * <ol> * <li>如果candidate的参数数量>0: * <ol> * <li>获取candidate的参数类型数组【变量 paramTypes】</li> * <li>使用该工厂的参数名发现器【parameterNameDiscoverer】获取candidate的参数名 【变量 paramNames】</li> * <li>获取mbd的构造函数参数值 【变量 cav】</li> * <li>定义一个存储构造函数参数值ValueHolder对象的HashSet【变量 usedValueHolders】</li> * <li>定义一个用于存储参数值的数组【变量 args】</li> * <li>遍历args,索引为i: * <ol> * <li>获取第i个构造函数参数值ValueHolder对象【变量 valueHolder】,尽可能的提供位置,参数类型,参数名 * 以最精准的方式获取获取第i个构造函数参数值ValueHolder对象,传入usedValueHolder来提示cav#getArgumentValue方法 * 不应再次返回该usedValueHolder所出现的ValueHolder对象(如果有 多个类型的通用参数值,则允许返回下一个通用参数匹配项)</li> * <li>如果valueHolder获取失败,使用不匹配类型,不匹配参数名的方式获取除userValueHolders以外的 * 下一个参数值valueHolder对象</li> * <li>如果valueHolder获取成功,从valueHolder中获取值保存到args[i],然后将valueHolder添加到usedValueHolders缓存中, * 表示该valueHolder已经使用过</li> * </ol> * </li> * <li>调用AutowireUtils.resolveReturnTypeForFactoryMethod(candidate, args, getBeanClassLoader())获取 * candidate的最终返回类型</li> * <li>如果commnType为null 且 returnType等于candidate直接获取的返回类型,uniqueCandidate就是candiate,否则为null</li> * <li>如果commonType为null就返回null,表示找到不明确的返回类型</li> * <li>捕捉获取commonType的所有异常,不再抛出任何异常,只打印出调试日志无法为工厂方法解析通用返回类型</li> * </ol> * </li> * <li>如果candidate无需参数: * <ol> * <li>如果还没有找到commonType,candidate就为uniqueCandidate</li> * <li>获取candidate返回类型与commonType的共同父类,将该父类重新赋值给commonType</li> * <li>如果commonType为null就返回null,表示找到不明确的返回类型</li> * </ol> * </li> * </ol> * </li> * <li>缓存uniqueCandidate到mbd的factoryMethodToInstropect</li> * <li>如果commonType为null就返回null,表示找到不明确的返回类型。加上这个判断能保证下面的步骤commonType肯定有值</li> * </ol> * </li> * <li>如果获取到了uniqueCandidate就获取uniqueCandidate的返回类型,否则就用commonType作为返回类型【变量cachedReturnType】</li> * <li>缓存cachedReturnType到mdb的factoryMethodReturnType</li> * <li>返回cachedReturnType封装的Class对象</li> * </ol> * </p> * Determine the target type for the given bean definition which is based on * a factory method. Only called if there is no singleton instance registered * for the target bean already. * <p>工厂方法确定给定bean定义的目标类型。仅在尚未为目标bean注册单例实例时调用</p> * <p>This implementation determines the type matching {@link #createBean}'s * different creation strategies. As far as possible, we'll perform static * type checking to avoid creation of the target bean. * <p>此实现确定与createBean的不同创建策略匹配的类型。尽可能地,我们将执行静态类型 * 检查以避免创建目标bean</p> * @param beanName the name of the bean (for error handling purposes) * -- bean名(用于错误处理) * @param mbd the merged bean definition for the bean * -- bean的合并bean定义 * @param typesToMatch the types to match in case of internal type matching purposes * (also signals that the returned {@code Class} will never be exposed to application code) * -- 内部类型匹配时要匹配的类型(也表示返回的Class永远不会暴露给应用程序代码) * @return the type for the bean if determinable, or {@code null} otherwise * -- Bean类型(如果可以确定的话),否则为 null * @see #createBean */ @Nullable protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { //尝试获取bean的合并bean定义中的缓存工厂方法返回类型 ResolvableType cachedReturnType = mbd.factoryMethodReturnType; //如果成功获取到了bean的合并bean定义中的缓存工厂方法返回类型 if (cachedReturnType != null) { //ResolvableType.resolve:将ResolvableType对象解析为Class,如果无法解析,则返回null return cachedReturnType.resolve(); } //通用的返回类型,经过比较 AutowireUtils#resolveReturnTypeForFactoryMethod方法的返回结果 // 和Method#getReturnType方法的返回结果所得到共同父类。 Class<?> commonType = null; //尝试获取bean的合并bean定义中的缓存用于自省的唯一工厂方法对象 Method uniqueCandidate = mbd.factoryMethodToIntrospect; //如果成功获取到了bean的合并bean定义中的缓存用于自省的唯一工厂方法对象 if (uniqueCandidate == null) { Class<?> factoryClass; boolean isStatic = true; //获取bean的合并bean定义的工厂bean名 String factoryBeanName = mbd.getFactoryBeanName(); //如果成功获取到bean的合并bean定义的工厂bean名 if (factoryBeanName != null) { //如果工厂bean名 与 生成该bean的bean名相等 if (factoryBeanName.equals(beanName)) { //抛出 当BeanFactory遇到无效的bean定义时引发的异常 : // 工厂bean引用指向相同的bean定义 throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition"); } // Check declared factory method return type on factory class. // 检查工厂类上声明的工厂方法返回类型 //获取factoryBeanName对应的工厂类 factoryClass = getType(factoryBeanName); isStatic = false; } else { // Check declared factory method return type on bean class. // 检查bean类上声明的工厂方法返回类型 //为mbd解析bean类,将bean类名解析为Class引用(如果需要),并将解析后的Class存储在 // mbd中以备将来使用。 factoryClass = resolveBeanClass(mbd, beanName, typesToMatch); } //如果mbd指定的工厂类获取失败 if (factoryClass == null) { //返回null return null; } //如果factoryClass是CGLIB生成的子类,则返回factoryClass的父类,否则直接返回factoryClass factoryClass = ClassUtils.getUserClass(factoryClass); // If all factory methods have the same return type, return that type. // Can't clearly figure out exact method due to type converting / autowiring! // 如果所有工厂方法都具有相同的返回类型,则返回该类型。 // 由于类型转换/自动装配,无法明确找出确切的方法。 // 如果mbd有配置构造函数参数值,就获取该构造函数参数值的数量,否则为0 int minNrOfArgs = (mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0); //在子类和所有超类上获取一组唯一的已声明方法,即被重写非协变返回类型的方法 // 首先包含子类方法和然后遍历父类层次结构任何方法,将过滤出所有与已包含的方法匹配的签名方法。 Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent(factoryClass, clazz -> ReflectionUtils.getUniqueDeclaredMethods(clazz, ReflectionUtils.USER_DECLARED_METHODS)); //遍历候选方法 for (Method candidate : candidates) { //如果candidate是否静态的判断结果与isStatic一致 且 candidate有资格作为工厂方法 且 candidate的方法参数数量>=minNrOfArgs if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) && candidate.getParameterCount() >= minNrOfArgs) { // Declared type variables to inspect? // 声明要检查的类型变量? // 如果candidate的参数数量>0 if (candidate.getTypeParameters().length > 0) { try { // Fully resolve parameter names and argument values. // 完全解析参数名称和参数值 // 获取candidate的参数类型数组 Class<?>[] paramTypes = candidate.getParameterTypes(); //参数名数组 String[] paramNames = null; //获取参数名发现器 ParameterNameDiscoverer pnd = getParameterNameDiscoverer(); //如果pnd不为null if (pnd != null) { //使用pnd获取candidate的参数名 paramNames = pnd.getParameterNames(candidate); } //获取mbd的构造函数参数值 ConstructorArgumentValues cav = mbd.getConstructorArgumentValues(); // HashSet:HashSet简单的理解就是HashSet对象中不能存储相同的数据,存储数据时是无序的。 // 但是HashSet存储元素的顺序并不是按照存入时的顺序(和List显然不同) 是按照哈希值来存的所以取数据也是按照哈希值取得。 // 定义一个存储构造函数参数值ValueHolder对象的HashSet Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length); // 定义一个用于存储参数值的数组 Object[] args = new Object[paramTypes.length]; //遍历参数值 for (int i = 0; i < args.length; i++) { //获取第i个构造函数参数值ValueHolder对象 //尽可能的提供位置,参数类型,参数名以最精准的方式获取获取第i个构造函数参数值ValueHolder对象,传入 // usedValueHolder来提示cav#getArgumentValue方法不应再次返回该usedValueHolder所出现的ValueHolder对象 // (如果有 多个类型的通用参数值,则允许返回下一个通用参数匹配项) ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue( i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders); //如果valueHolder获取失败 if (valueHolder == null) { //使用不匹配类型,不匹配参数名的方式获取除userValueHolders以外的下一个参数值valueHolder对象 valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders); } //如果valueHolder获取成功 if (valueHolder != null) { //从valueHolder中获取值保存到第i个args元素中 args[i] = valueHolder.getValue(); //将valueHolder添加到usedValueHolders缓存中,表示该valueHolder已经使用过 usedValueHolders.add(valueHolder); } } //获取candidate的最终返回类型,该方法支持泛型情况下的目标类型获取 Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod( candidate, args, getBeanClassLoader()); //如果commnType为null 且 returnType等于candidate直接获取的返回类型,唯一候选方法就是candiate,否则为null uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ? candidate : null); //获取returnType与commonType的共同父类,将该父类重新赋值给commonType commonType = ClassUtils.determineCommonAncestor(returnType, commonType); //如果commonType为null if (commonType == null) { // Ambiguous return types found: return null to indicate "not determinable". // 找到不明确的返回类型:返回null表示'不可确定' return null; } } //捕捉获取commonType的所有异常 catch (Throwable ex) { if (logger.isDebugEnabled()) { //无法为工厂方法解析通用返回类型 logger.debug("Failed to resolve generic return type for factory method: " + ex); } } } //如果candidate无需参数 else { //如果还没有找到commonType,candidate就为唯一的候选方法 uniqueCandidate = (commonType == null ? candidate : null); //获取candidate返回类型与commonType的共同父类,将该父类重新赋值给commonType commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType); //如果commonType为null if (commonType == null) { // Ambiguous return types found: return null to indicate "not determinable". // 找到不明确的返回类型:返回null表示'不可确定' return null; } } } } //缓存uniqueCandidate到mbd的factoryMethodToInstropect mbd.factoryMethodToIntrospect = uniqueCandidate; //如果commonType为null,加上这个判断能保证下面的步骤commonType肯定有值 if (commonType == null) { // 找到不明确的返回类型:返回null表示'不可确定' return null; } } // Common return type found: all factory methods return same type. For a non-parameterized // unique candidate, cache the full type declaration context of the target factory method. // 找到常见的返回类型:所有工厂方法都返回相同的类型。对象非参数化的唯一候选者,缓存目标工厂方法的 // 完整类型声明上下文 //如果获取到了uniqueCandidate就获取uniqueCandidate的返回类型,否则就用commonType作为返回类型 cachedReturnType = (uniqueCandidate != null ? ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType)); //缓存cachedReturnType到mdb的factoryMethodReturnType mbd.factoryMethodReturnType = cachedReturnType; //返回cachedReturnType封装的Class对象 return cachedReturnType.resolve(); } /** * This implementation attempts to query the FactoryBean's generic parameter metadata * if present to determine the object type. If not present, i.e. the FactoryBean is * declared as a raw type, checks the FactoryBean's {@code getObjectType} method * on a plain instance of the FactoryBean, without bean properties applied yet. * If this doesn't return a type yet, and {@code allowInit} is {@code true} a * full creation of the FactoryBean is used as fallback (through delegation to the * superclass's implementation). * <p>The shortcut check for a FactoryBean is only applied in case of a singleton * FactoryBean. If the FactoryBean instance itself is not kept as singleton, * it will be fully created to check the type of its exposed object. */ @Override protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) { // Check if the bean definition itself has defined the type with an attribute ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd); if (result != ResolvableType.NONE) { return result; } ResolvableType beanType = (mbd.hasBeanClass() ? ResolvableType.forClass(mbd.getBeanClass()) : ResolvableType.NONE); // For instance supplied beans try the target type and bean class if (mbd.getInstanceSupplier() != null) { result = getFactoryBeanGeneric(mbd.targetType); if (result.resolve() != null) { return result; } result = getFactoryBeanGeneric(beanType); if (result.resolve() != null) { return result; } } // Consider factory methods String factoryBeanName = mbd.getFactoryBeanName(); String factoryMethodName = mbd.getFactoryMethodName(); // Scan the factory bean methods if (factoryBeanName != null) { if (factoryMethodName != null) { // Try to obtain the FactoryBean's object type from its factory method // declaration without instantiating the containing bean at all. BeanDefinition factoryBeanDefinition = getBeanDefinition(factoryBeanName); Class<?> factoryBeanClass; if (factoryBeanDefinition instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) factoryBeanDefinition).hasBeanClass()) { factoryBeanClass = ((AbstractBeanDefinition) factoryBeanDefinition).getBeanClass(); } else { RootBeanDefinition fbmbd = getMergedBeanDefinition(factoryBeanName, factoryBeanDefinition); factoryBeanClass = determineTargetType(factoryBeanName, fbmbd); } if (factoryBeanClass != null) { result = getTypeForFactoryBeanFromMethod(factoryBeanClass, factoryMethodName); if (result.resolve() != null) { return result; } } } // If not resolvable above and the referenced factory bean doesn't exist yet, // exit here - we don't want to force the creation of another bean just to // obtain a FactoryBean's object type... if (!isBeanEligibleForMetadataCaching(factoryBeanName)) { return ResolvableType.NONE; } } // If we're allowed, we can create the factory bean and call getObjectType() early if (allowInit) { FactoryBean<?> factoryBean = (mbd.isSingleton() ? getSingletonFactoryBeanForTypeCheck(beanName, mbd) : getNonSingletonFactoryBeanForTypeCheck(beanName, mbd)); if (factoryBean != null) { // Try to obtain the FactoryBean's object type from this early stage of the instance. Class<?> type = getTypeForFactoryBean(factoryBean); if (type != null) { return ResolvableType.forClass(type); } // No type found for shortcut FactoryBean instance: // fall back to full creation of the FactoryBean instance. return super.getTypeForFactoryBean(beanName, mbd, true); } } if (factoryBeanName == null && mbd.hasBeanClass() && factoryMethodName != null) { // No early bean instantiation possible: determine FactoryBean's type from // static factory method signature or from class inheritance hierarchy... return getTypeForFactoryBeanFromMethod(mbd.getBeanClass(), factoryMethodName); } result = getFactoryBeanGeneric(beanType); if (result.resolve() != null) { return result; } return ResolvableType.NONE; } private ResolvableType getFactoryBeanGeneric(@Nullable ResolvableType type) { if (type == null) { return ResolvableType.NONE; } return type.as(FactoryBean.class).getGeneric(); } /** * Introspect the factory method signatures on the given bean class, * trying to find a common {@code FactoryBean} object type declared there. * @param beanClass the bean class to find the factory method on * @param factoryMethodName the name of the factory method * @return the common {@code FactoryBean} object type, or {@code null} if none */ private ResolvableType getTypeForFactoryBeanFromMethod(Class<?> beanClass, String factoryMethodName) { // CGLIB subclass methods hide generic parameters; look at the original user class. Class<?> factoryBeanClass = ClassUtils.getUserClass(beanClass); FactoryBeanMethodTypeFinder finder = new FactoryBeanMethodTypeFinder(factoryMethodName); ReflectionUtils.doWithMethods(factoryBeanClass, finder, ReflectionUtils.USER_DECLARED_METHODS); return finder.getResult(); } /** * This implementation attempts to query the FactoryBean's generic parameter metadata * if present to determine the object type. If not present, i.e. the FactoryBean is * declared as a raw type, checks the FactoryBean's {@code getObjectType} method * on a plain instance of the FactoryBean, without bean properties applied yet. * If this doesn't return a type yet, a full creation of the FactoryBean is * used as fallback (through delegation to the superclass's implementation). * <p>The shortcut check for a FactoryBean is only applied in case of a singleton * FactoryBean. If the FactoryBean instance itself is not kept as singleton, * it will be fully created to check the type of its exposed object. */ @Override @Deprecated @Nullable protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) { return getTypeForFactoryBean(beanName, mbd, true).resolve(); } /** * <p>该方法由 ObjectFactory实例的 getObject 方法 调用</p> * Obtain a reference for early access to the specified bean, * typically for the purpose of resolving a circular reference. * <p>获取对 指定Bean 的 早期访问引用,通常用于解决循环引用</p> * @param beanName the name of the bean (for error handling purposes) -- bean的名称(用于处理错误) * @param mbd the merged bean definition for the bean -- 合并后的BeanDefinition对象 * @param bean the raw bean instance -- 原始Bean实例 * @return the object to expose as bean reference -- 要公开为bean引用的对象 */ protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) { //默认最终公开的对象是bean Object exposedObject = bean; //mbd的systheic属性:设置此bean定义是否是"synthetic",一般是指只有AOP相关的prointCut配置或者Advice配置才会将 synthetic设置为true //如果 mdb不是syntheic 且 此工厂拥有InstiationAwareBeanPostProcessor if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //遍历 工厂内的所有后处理器 for (BeanPostProcessor bp : getBeanPostProcessors()) { //如果 bp 是 SmartInstantiationAwareBeanPostProcessor实例 if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; //让exposedObject经过每个SmartInstantiationAwareBeanPostProcessor的包装 exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); } } } //返回最终经过层次包装后的对象 return exposedObject; } //--------------------------------------------------------------------- // Implementation methods //--------------------------------------------------------------------- /** * Obtain a "shortcut" singleton FactoryBean instance to use for a * {@code getObjectType()} call, without full initialization of the FactoryBean. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @return the FactoryBean instance, or {@code null} to indicate * that we couldn't obtain a shortcut FactoryBean instance */ @Nullable private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { synchronized (getSingletonMutex()) { BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName); if (bw != null) { return (FactoryBean<?>) bw.getWrappedInstance(); } Object beanInstance = getSingleton(beanName, false); if (beanInstance instanceof FactoryBean) { return (FactoryBean<?>) beanInstance; } if (isSingletonCurrentlyInCreation(beanName) || (mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) { return null; } Object instance; try { // Mark this bean as currently in creation, even if just partially. beforeSingletonCreation(beanName); // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. instance = resolveBeforeInstantiation(beanName, mbd); if (instance == null) { bw = createBeanInstance(beanName, mbd, null); instance = bw.getWrappedInstance(); } } catch (UnsatisfiedDependencyException ex) { // Don't swallow, probably misconfiguration... throw ex; } catch (BeanCreationException ex) { // Instantiation failure, maybe too early... if (logger.isDebugEnabled()) { logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } finally { // Finished partial creation of this bean. afterSingletonCreation(beanName); } FactoryBean<?> fb = getFactoryBean(beanName, instance); if (bw != null) { this.factoryBeanInstanceCache.put(beanName, bw); } return fb; } } /** * Obtain a "shortcut" non-singleton FactoryBean instance to use for a * {@code getObjectType()} call, without full initialization of the FactoryBean. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @return the FactoryBean instance, or {@code null} to indicate * that we couldn't obtain a shortcut FactoryBean instance */ @Nullable private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { if (isPrototypeCurrentlyInCreation(beanName)) { return null; } Object instance; try { // Mark this bean as currently in creation, even if just partially. beforePrototypeCreation(beanName); // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. instance = resolveBeforeInstantiation(beanName, mbd); if (instance == null) { BeanWrapper bw = createBeanInstance(beanName, mbd, null); instance = bw.getWrappedInstance(); } } catch (UnsatisfiedDependencyException ex) { // Don't swallow, probably misconfiguration... throw ex; } catch (BeanCreationException ex) { // Instantiation failure, maybe too early... if (logger.isDebugEnabled()) { logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } finally { // Finished partial creation of this bean. afterPrototypeCreation(beanName); } return getFactoryBean(beanName, instance); } /** * Apply MergedBeanDefinitionPostProcessors to the specified bean definition, * invoking their {@code postProcessMergedBeanDefinition} methods. * <p>将 MergedBeanDefinitionPostProcessors 应用到指定的 BeanDefinition ,调用它们的 * postProcessMergedBeanDefinition 方法</p> * @param mbd the merged bean definition for the bean -- bean的合并后beanDefinition * @param beanType the actual type of the managed bean instance -- 托管bean实例的实际类型 * @param beanName the name of the bean -- bean名 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition */ protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) { //遍历工厂创建的bean的BeanPostProcessors列表 for (BeanPostProcessor bp : getBeanPostProcessors()) { // 如果 bp 是 MergedBeanDefinitionPostProcessor 的实例 if (bp instanceof MergedBeanDefinitionPostProcessor) { MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp; //回调postProcessMergedBeanDefinition方法,一般MergedBeanDefinitionPostProcessor会做一些 内省BeanDefinition, // 以便对bean 的实际实例进行后处理之前准备一些缓存的元数据,它也可以修改beanDefinition,但只允许用于实际用于并发 修改的Befinition属性。 // 本质上,这只适用于在RootBeanDefinition本身定义的操作,而不适用于其基类 bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName); } } } /** * <p>应用InstantiationAwareBeanPostProcessor后处理器实例化benName的实例对象: * <ol> * <li>定义一个【变量bean】默认为null,表示没有InstantiationAwareBeanPostProcessor后处理器 * 可实例化beanName的实例对象</li> * <li>如果mdb还没有启动实例化前的后处理器【RootBeanDefinition#beforeInstantiationResolved】: * <ol> * <li>如果mbd不是合成的 且 该工厂拥有InstiationAwareBeanPostProcessor: * <ol> * <li>确定mbd的目标类型,【变量targetType】</li> * <li>如果成功获取到了targetType: * <ol> * <li>在实例化之前应用 InstantiationAwareBeanPostProcessor 后处理器,并尝试通过BeanPostProcess创建 * beanName&beanClass的单例对象 【变量 bean】</li> * <li>如果成功获取bean,就应用所有BeanPostProcess对bean进行后处理包装。</li> * </ol> * </li> * </ol> * </li> * <li>当bean实例化成功后,对mbd加上已启动实例化前的后处理器的标记【RootBeanDefinition#beforeInstantiationResolved】</li> * </ol> * </li> * <li>返回bean</li> * </ol> * </p> * Apply before-instantiation post-processors, resolving whether there is a * before-instantiation shortcut for the specified bean. * <p>应用实例化之前的后处理器,以解决指定的bean是否存在实例化快捷方式</p> * @param beanName the name of the bean --bean名 * @param mbd the bean definition for the bean -- bean的合并后BeanDefinition * @return the shortcut-determined bean instance, or {@code null} if none * -- 快捷方式确定的bean实例;如果没有,则未null */ @Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { //定义一个变量bean,默认为null,表示没有InstantiationAwareBeanPostProcessor后处理器可实例化beanName的实例对象 Object bean = null; //如果mdb还没有启动实例化前的后处理器 if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. // 确保此时确实解决了bean类 //如果mbd不是合成的 且 该工厂拥有InstiationAwareBeanPostProcessor if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //确定mbd的目标类型 Class<?> targetType = determineTargetType(beanName, mbd); //如果成功获取到了目标类型 if (targetType != null) { //在实例化之前应用 InstantiationAwareBeanPostProcessor 后处理器,并尝试通过Bean后处理器创建beanName&beanClass的单例对象 bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); //如果成功获取单例对象 if (bean != null) { //在实例化之后,应用所有BeanPostProcess对bean进行后处理包装。 bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } //当bean实例化成功后,对mbd加上已启动实例化前的后处理器的标记 mbd.beforeInstantiationResolved = (bean != null); } return bean; } /** * <p> * 在实例化之前应用Bean后处理器,并尝试通过Bean后处理器创建beanName&beanClass的单例对象 * <ol> * <li>遍历该工厂创建的bean的BeanPostProcessors列表,元素为bp: * <ol> * <li>如果 bp 是 InstantiationAwareBeanPostProcessor 的实例: * <ol> * <li>将 bp 强转为InstantiationAwareBeanPostProcessor对象</li> * <li>调用postProcessBeforeInstantiation方法得到beanName指定的实例对象</li> * <li>如果该实例对象获取成功,直接返回该实例对象</li> * </ol> * </li> * </ol> * </li> * <li>返回null,表示该beanClass/beanName未能通过InstantiationAwareBeanPostProcessor实例化出指定实例对象</li> * </ol> * </p> * Apply InstantiationAwareBeanPostProcessors to the specified bean definition * (by class and name), invoking their {@code postProcessBeforeInstantiation} methods. * <p>将 InstantiationAwareBeanPostProcessors 应用于指定的beanDefinition(按类和名称),并 * 调用他们的 postProcessBeforeInstantiation 方法</p> * <p>Any returned object will be used as the bean instead of actually instantiating * the target bean. A {@code null} return value from the post-processor will * result in the target bean being instantiated. * <p>任何返回的对象都将用做bean,而不是实际实例化目标bean。后置处理器返回的空值将导致目标bean * 被实例化。</p> * @param beanClass the class of the bean to be instantiated -- 要实例化的bean类型 * @param beanName the name of the bean -- bean名 * @return the bean object to use instead of a default instance of the target bean, or {@code null} * -- 要使用bean的bean对象,而不是目标的默认实例,或 null * @see InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation */ @Nullable protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) { //遍历该工厂创建的bean的BeanPostProcessors列表 for (BeanPostProcessor bp : getBeanPostProcessors()) { //如果 bp 是 InstantiationAwareBeanPostProcessor 的实例 if (bp instanceof InstantiationAwareBeanPostProcessor) { //将 bp 强转为InstantiationAwareBeanPostProcessor对象 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //调用postProcessBeforeInstantiation方法得到beanName指定的实例对象 Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); //如果该实例对象获取成功 if (result != null) { //也就是说如果出现多个InstantiationAwareBeanPostProcessor实例都可对beanName进行创建 //其实例对象,也是会按照BeanPostProcessors列表的顺序,谁第一个被调用就用谁。 //直接返回出去 return result; } } } //返回null,表示该beanClass/beanName未能通过InstantiationAwareBeanPostProcessor实例化出指定实例对象 return null; } /** * 使用适当的实例化策略为指定的Bean创建一个新实例:工厂方法,构造函数自动装配或简单实例化。 * <ol> * <li>使用工厂方法(多个工厂方法时,会找到最匹配的那个构造函数),优先使用 args的参数值来实例化对象, * 没有就使用mdb所定义的参数值</li> * <li>使用构造函数: * <ol> * <li>从SmartInstantiationAwareBeanPostProcessor中获取给定bean的候选构造函数 || * mdb的解析自动注入模式为 按构造器自动装配 || mbd有构造函数参数 || args不为null,会以自动注入 * 方式调用最匹配的构造函数来实例化参数对象并返回出去</li> * <li>从mbd中获取首选的构造函数,以自动注入方式调用最匹配的构造函数来实例化参数对象并返回出去</li> * <li>无须特殊处理,只需使用无参数的构造函数</li> * </ol> * </li> * </ol> * Create a new instance for the specified bean, using an appropriate instantiation strategy: * factory method, constructor autowiring, or simple instantiation. * <p>使用适当的实例化策略为指定的Bean创建一个新实例:工厂方法,构造函数自动装配或简单实例化。</p> * @param beanName the name of the bean -- bean名 * @param mbd the bean definition for the bean -- bean的BeanDefinition * @param args explicit arguments to use for constructor or factory method invocation * -- 用于构造函数或工厂方法调用的显示参数 * @return a BeanWrapper for the new instance -- 新实例的BeanWrapper * @see #obtainFromSupplier * @see #instantiateUsingFactoryMethod * @see #autowireConstructor * @see #instantiateBean */ protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. // 确保此时确实解决了bean类 //获取mdb解析出对应的bean class Class<?> beanClass = resolveBeanClass(mbd, beanName); //如果成功获取到beanClass且beanClass不是用public且mbd不允许访问非公共构造函数和方法 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { //抛出Bean创建异常:bean类不是公共的,并且不允许非公共访问 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } //获取创建bean定义的回调对象 Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); //如果有回调对象 if (instanceSupplier != null) { //从instanceSupplier那里获取一个bean实例,并对其包装成BeanWrapper对象: return obtainFromSupplier(instanceSupplier, beanName); } //如果mbd有配置工厂方法名 if (mbd.getFactoryMethodName() != null) { //使用命名工厂方法实例化beanName所对应的bean对象 return instantiateUsingFactoryMethod(beanName, mbd, args); } //没有工厂方法的情况 // Shortcut when re-creating the same bean... // 重新创建相同Bena的快捷方式 //是否已解析出构造函数标记,默认为false,表示还没有解析 boolean resolved = false; //必须要自动注入标记,默认为false,表示不需要 boolean autowireNecessary = false; //如果args为null if (args == null) { //使用mbd的构造函数通用锁【{@link RootBeanDefinition#constructorArgumentLock}】加锁以保证线程安全: synchronized (mbd.constructorArgumentLock) { //如果mdb的已解析的构造函数或工厂方法【{@link RootBeanDefinition#resolvedConstructorOrFactoryMethod}】不为null if (mbd.resolvedConstructorOrFactoryMethod != null) { //设置resloved为true,表示已解析 resolved = true; //让autowireNecessary引用mbd的构造函数参数已解析标记值【{@link RootBeanDefinition#constructorArgumentsResolved}】, // 如果构造函数参数已解析,表示必须要自动注入;否则不需要自动注入 autowireNecessary = mbd.constructorArgumentsResolved; } } } //如果已解析出构造函数 if (resolved) { //如果必须要自动注入 if (autowireNecessary) { //以自动注入方式调用最匹配的构造函数来实例化参数对象并返回出去 return autowireConstructor(beanName, mbd, null, null); } else { //使用其默认构造函数实例化给定的Bean并返回出去 return instantiateBean(beanName, mbd); } } // Candidate constructors for autowiring? // 自动装配的候选构造函数? //从SmartInstantiationAwareBeanPostProcessor中获取给定bean的候选构造函数 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); //如果ctors不为null || mdb的解析自动注入模式为 按构造器自动装配 || mbd有构造函数参数 || args不为null if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { //以自动注入方式调用最匹配的构造函数来实例化参数对象并返回出去 return autowireConstructor(beanName, mbd, ctors, args); } // Preferred constructors for default construction? // 默认构造的首选构造函数 ctors = mbd.getPreferredConstructors(); //ctor不为null if (ctors != null) { //以自动注入方式调用最匹配的构造函数来实例化参数对象并返回出去 return autowireConstructor(beanName, mbd, ctors, null); } // No special handling: simply use no-arg constructor. // 无须特殊处理,只需使用无参数的构造函数 return instantiateBean(beanName, mbd); } /** * <p>从给定的供应商那里获取一个bean实例,并对其包装成BeanWrapper对象: * <ol> * <li>声明一个实例对象【变量 instance】</li> * <li>从线程本地当前创建的bean名称【currentlyCreatedBean】中获取原先创建bean的名字【变量 outerBean】</li> * <li>保存beanName到currentlyCreatedBean中</li> * <li>从配置的Supplier中获取一个bean实例,赋值instance</li> * <li>【finally】如果原先bean存在,将保存到currentlyCreatedBean中;否则就将beanName移除</li> * <li>如果没有成功获取到instance,instance就引用NullBean</li> * <li>对instance包装成BeanWrapper对象【变量 bw】</li> * <li>初始化bw 【{@link #initBeanWrapper(BeanWrapper)}】</li> * <li>返回初始化后的bw</li> * </ol> * </p> * Obtain a bean instance from the given supplier. * <p>从给定的供应商那里获取一个bean实例</p> * @param instanceSupplier the configured supplier -- 配置的供应商 * @param beanName the corresponding bean name -- 对应的bean名 * @return a BeanWrapper for the new instance -- 新实例的BeanWrapper * @since 5.0 * @see #getObjectForBeanInstance */ protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) { //实例对象 Object instance; //从线程本地当前创建的bean名称【currentlyCreatedBean】中获取原先创建bean的名字 String outerBean = this.currentlyCreatedBean.get(); //保存新的bean的名字到currentlyCreatedBean中 this.currentlyCreatedBean.set(beanName); try { //从配置的Supplier中获取一个bean实例 instance = instanceSupplier.get(); } finally { //如果原先bean存在,将保存到currentlyCreatedBean中 if (outerBean != null) { this.currentlyCreatedBean.set(outerBean); } else { //如果没有就将beanName移除 this.currentlyCreatedBean.remove(); } } //如果没有成功获取到bean实例 if (instance == null) { //bean实例就引用NullBean instance = new NullBean(); } // BeanWrapperImpl类是对BeanWrapper接口的默认实现,它包装了一个bean对象, // 缓存了bean的内省结果, 并可以访问bean的属性、设置bean的属性值。BeanWrapperImpl // 类提供了许多默认属性编辑器, 支持多种不同类型的类型转换,可以将数组、集合类型的属 // 性转换成指定特殊类型的数组或集合。 用户也可以注册自定义的属性编辑器在BeanWrapperImpl中。 //对instance进行包装 BeanWrapper bw = new BeanWrapperImpl(instance); //初始化包装对象 initBeanWrapper(bw); //返回初始化后的bw return bw; } /** * Overridden in order to implicitly register the currently created bean as * dependent on further beans getting programmatically retrieved during a * {@link Supplier} callback. * @since 5.0 * @see #obtainFromSupplier */ @Override protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) { String currentlyCreatedBean = this.currentlyCreatedBean.get(); if (currentlyCreatedBean != null) { registerDependentBean(beanName, currentlyCreatedBean); } return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd); } /** * <p>从SmartInstantiationAwareBeanPostProcessor中获取给定bean的候选构造函数</p> * Determine candidate constructors to use for the given bean, checking all registered * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}. * <p>确定为给定的bean使用的候选构造函数,检查所有已注册的 SmartInstantiationAwareBeanPostProcessors</p> * @param beanClass the raw class of the bean -- bean的原始类 * @param beanName the name of the bean -- bean名 * @return the candidate constructors, or {@code null} if none specified -- 候选构造函数,或 null (如果没有指定) * @throws org.springframework.beans.BeansException in case of errors -- 以防出现错误 * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors */ @Nullable protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException { //如果 beanClas 不为null 且 此工厂拥有InstiationAwareBeanPostProcessor if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { //遍历BeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { //如果 bp 是 SmartInstantiationAwareBeanPostProcessor 实例 if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; //从ibp中获取指定的候选构造函数 Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; } } } } return null; } /** * Instantiate the given bean using its default constructor. * <p>使用其默认构造函数实例化给定的Bean</p> * @param beanName the name of the bean -- bean名 * @param mbd the bean definition for the bean -- bean的beanDefinition * @return a BeanWrapper for the new instance -- 新实例的BeanWrapper实例 */ protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { try { Object beanInstance; final BeanFactory parent = this; //如果安全管理器,就使用特权方式 获取实例化策略对象进行实例化对象 if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, parent), getAccessControlContext()); } else { //否则,直接获取实例化策略对象进行实例化对象 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); } //包装bean对象 BeanWrapper bw = new BeanWrapperImpl(beanInstance); //初始化 bw initBeanWrapper(bw); return bw; } catch (Throwable ex) { //捕捉所有实例化对象时抛出的异常,重新抛出创建BeanCreateException异常 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } } /** * Instantiate the bean using a named factory method. The method may be static, if the * mbd parameter specifies a class, rather than a factoryBean, or an instance variable * on a factory object itself configured using Dependency Injection. * <p>使用命名工厂方法实例化bean。如果mbd参数指定一个类(而不是factoryBean)或使用依赖注入配置 * 的工厂对象本身的实例变量,则该方法可以是静态的。</p> * @param beanName the name of the bean -- bean名 * @param mbd the bean definition for the bean -- bean的BeanDefinition * @param explicitArgs argument values passed in programmatically via the getBean method, * or {@code null} if none (-> use constructor argument values from bean definition) * -- 通过getBean方法以编程方式传递的参数值;如果没有,则返回null(->使用bean定义的构造函数参数值) * @return a BeanWrapper for the new instance -- 新实例的BeanWrapper * @see #getBean(String, Object[]) */ protected BeanWrapper instantiateUsingFactoryMethod( String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) { //实例化一个新的ConstructorResolver对象,让其使用工厂方法实例化beanName所对应的Bean对象: return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs); } /** * <p>以自动注入方式调用最匹配的构造函数来实例化参数对象</p> * "autowire constructor" (with constructor arguments by type) behavior. * Also applied if explicit constructor argument values are specified, * matching all remaining arguments with beans from the bean factory. * <p>"autowire constructor"(按类型带有构造函数参数)的行为。如果显示指定了构造函数自变量值, * 则将所有剩余自变量与Bean工厂中的Bean进行匹配时也适用</p> * <p>This corresponds to constructor injection: In this mode, a Spring * bean factory is able to host components that expect constructor-based * dependency resolution. * <p>这对应于构造函数注入:在这种模式下,Spring Bean工厂能够托管需要基于构造函数数的 * 依赖关系解析的组件</p> * @param beanName the name of the bean -- Bean名 * @param mbd the bean definition for the bean -- Bean的BeanDefinition * @param ctors the chosen candidate constructors -- 选择的候选构造函数 * @param explicitArgs argument values passed in programmatically via the getBean method, * or {@code null} if none (-> use constructor argument values from bean definition) * -- 用于构造函数或工厂方法调用的显示参数 * @return a BeanWrapper for the new instance -- 新实例的BeanWrapper */ protected BeanWrapper autowireConstructor( String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) { //实例化一个新的ConstructorResolver对象,以自动注入方式调用最匹配的构造函数来实例化参数对象 return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs); } /** * Populate the bean instance in the given BeanWrapper with the property values * from the bean definition. * <p>用来自 BeanDefinition的属性值填充给定的BeanWrapper中的bean实例</p> * @param beanName the name of the bean -- bean的名称 * @param mbd the bean definition for the bean -- bean的beanDefinition * @param bw the BeanWrapper with bean instance -- 带有bean实例的bean包装器 */ @SuppressWarnings("deprecation") // for postProcessPropertyValues 对于postProcessPropertyValues protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { //如果bw为null if (bw == null) { //如果mdb有需要设置的属性 if (mbd.hasPropertyValues()) { //抛出Bean创建异常 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 跳过 null 实例的属性填充阶段 return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 给任何 InstantiationAwareBeanPostProcessors 会在属性设置之前修改bean的状态,这可以支持字段注入的样式 // 字段注入的样式 //继续对bean对象属性赋值的标记 boolean continueWithPropertyPopulation = true; //否是"synthetic"。一般是指只有AOP相关的prointCut配置或者Advice配置才会将 synthetic设置为true //如果mdb是不是'syntheic' 且 工厂拥有InstiationAwareBeanPostProcessor if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //遍历工厂中的BeanPostProcessor对象 for (BeanPostProcessor bp : getBeanPostProcessors()) { //如果 bp 是 InstantiationAwareBeanPostProcessor 实例 if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //postProcessAfterInstantiation:一般用于设置属性 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { //如果postProcessAfterInstantiation返回false,则不再调用任何后续的InstantiationAwareBeanPostProcessor实例 // 也不再调用 populateBean 的后续逻辑 continueWithPropertyPopulation = false; break; } } } } //如果不需要调用 populateBean 的后续逻辑,就结束改方法 if (!continueWithPropertyPopulation) { return; } //PropertyValues:包含以一个或多个PropertyValue对象的容器,通常包括针对特定目标Bean的一次更新 //如果mdb有PropertyValues就获取其PropertyValues PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 获取 mbd 的 自动装配模式 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); // 如果 自动装配模式 为 按名称自动装配bean属性 或者 按类型自动装配bean属性 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { //MutablePropertyValues:PropertyValues接口的默认实现。允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 根据autotowire的名称(如适用)添加属性值 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { //通过bw的PropertyDescriptor属性名,查找出对应的Bean对象,将其添加到newPvs中 autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. // 根据自动装配的类型(如果适用)添加属性值 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { //通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到newPvs中 autowireByType(beanName, mbd, bw, newPvs); } //让pvs重新引用newPvs,newPvs此时已经包含了pvs的属性值以及通过AUTOWIRE_BY_NAME,AUTOWIRE_BY_TYPE自动装配所得到的属性值 pvs = newPvs; } //工厂是否拥有InstiationAwareBeanPostProcessor boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); //mbd.getDependencyCheck(),默认返回 DEPENDENCY_CHECK_NONE,表示 不检查 //是否需要依赖检查 boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); //经过筛选的PropertyDesciptor数组,存放着排除忽略的依赖项或忽略项上的定义的属性 PropertyDescriptor[] filteredPds = null; //如果工厂拥有InstiationAwareBeanPostProcessor if (hasInstAwareBpps) { //如果pvs为null if (pvs == null) { //尝试获取mbd的PropertyValues pvs = mbd.getPropertyValues(); } //遍历工厂内的所有后置处理器 for (BeanPostProcessor bp : getBeanPostProcessors()) { //如果 bp 是 InstantiationAwareBeanPostProcessor 的实例 if (bp instanceof InstantiationAwareBeanPostProcessor) { //将bp 强转成 InstantiationAwareBeanPostProcessor 对象 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //postProcessProperties:在工厂将给定的属性值应用到给定Bean之前,对它们进行后处理,不需要任何属性扫描符。该回调方法在未来的版本会被删掉。 // -- 取而代之的是 postProcessPropertyValues 回调方法。 // 让ibp对pvs增加对bw的Bean对象的propertyValue,或编辑pvs的proertyValue PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); //如果pvs为null if (pvsToUse == null) { //如果filteredPds为null if (filteredPds == null) { //mbd.allowCaching:是否允许缓存,默认时允许的。缓存除了可以提高效率以外,还可以保证在并发的情况下,返回的PropertyDesciptor[]永远都是同一份 //从bw提取一组经过筛选的PropertyDesciptor,排除忽略的依赖项或忽略项上的定义的属性 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } //postProcessPropertyValues:一般进行检查是否所有依赖项都满足,例如基于"Require"注释在 bean属性 setter, // -- 替换要应用的属性值,通常是通过基于原始的PropertyValues创建一个新的MutablePropertyValue实例, 添加或删除特定的值 // -- 返回的PropertyValues 将应用于bw包装的bean实例 的实际属性值(添加PropertyValues实例到pvs 或者 设置为null以跳过属性填充) //回到ipd的postProcessPropertyValues方法 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); //如果pvsToUse为null,将终止该方法精致,以跳过属性填充 if (pvsToUse == null) { return; } } //让pvs引用pvsToUse pvs = pvsToUse; } } } //如果需要依赖检查 if (needsDepCheck) { //如果filteredPds为null if (filteredPds == null) { //从bw提取一组经过筛选的PropertyDesciptor,排除忽略的依赖项或忽略项上的定义的属性 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } //检查依赖项:主要检查pd的setter方法需要赋值时,pvs中有没有满足其pd的需求的属性值可供其赋值 checkDependencies(beanName, mbd, filteredPds, pvs); } //如果pvs不为null if (pvs != null) { //应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 不会永久地修改这个属性 applyPropertyValues(beanName, mbd, bw, pvs); } } /** * <p> 通过bw的PropertyDescriptor属性名,查找出对应的Bean对象,将其添加到pvs中 </p> * Fill in any missing property values with references to * other beans in this factory if autowire is set to "byName". * <p>如果autowire被设置为"byName",则用对工厂中其他bean的引用填充任何缺失的属性值</p> * @param beanName the name of the bean we're wiring up. * Useful for debugging messages; not used functionally. * -- 我们要连接的bean的名称。用于调试消息;未使用的功能 * @param mbd bean definition to update through autowiring * -- 通过自动装配来更新BeanDefinition * @param bw the BeanWrapper from which we can obtain information about the bean * -- 我们可以从中获取关于bean的信息的BeanWrapper * @param pvs the PropertyValues to register wired objects with * -- 要向其注册连接对象的 PropertyValues */ protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { //获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); //遍历属性名 for (String propertyName : propertyNames) { //如果该bean工厂有propertyName的beanDefinition或外部注册的singleton实例 if (containsBean(propertyName)) { //获取该工厂中propertyName的bean对象 Object bean = getBean(propertyName); //将propertyName,bean添加到pvs中 pvs.add(propertyName, bean); //注册propertyName与beanName的依赖关系 registerDependentBean(propertyName, beanName); //打印跟踪日志 if (logger.isTraceEnabled()) { // 从 bean名称中添加名称自动装配 'beanName' 通过 property 'propertyName' 到 bean 名为 'propertyName' logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { //打印跟踪日志 if (logger.isTraceEnabled()) { // 不能通过bean名方式自动装配属性 'propertyName':没有找到匹配的bean logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } } /** * <p> 通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到pvs中 </p> * Abstract method defining "autowire by type" (bean properties by type) behavior. * <p>定义 "按类型自动装配" (按类型bean属性)行为的抽象方法</p> * <p>This is like PicoContainer default, in which there must be exactly one bean * of the property type in the bean factory. This makes bean factories simple to * configure for small namespaces, but doesn't work as well as standard Spring * behavior for bigger applications. * <p>这类似于PicoContainer默认值,其中bean工厂中必须恰好有一个属性类型的bean。这使得针对 * 小名称空间配置bean工厂变得简单,但是对于较大的应用程序,它的工作效果不如标准的Spring行为。</p> * @param beanName the name of the bean to autowire by type -- 要按类型自动连接的bean的名称 * @param mbd the merged bean definition to update through autowiring * -- 合并后的BeanDefinition更新通过自动装配 * @param bw the BeanWrapper from which we can obtain information about the bean * -- 我们可以从中获取关于bean的信息的BeanWrapper * @param pvs the PropertyValues to register wired objects with * -- propertyValue 注册连接对象 */ protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { //获取工厂的自定义类型转换器 TypeConverter converter = getCustomTypeConverter(); //如果没有配置自定义类型转换器 if (converter == null) { //使用bw作为类型转换器 converter = bw; } //存放所有候选Bean名的集合 Set<String> autowiredBeanNames = new LinkedHashSet<>(4); //获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); //遍历属性名数组 for (String propertyName : propertyNames) { try { //PropertyDescriptor:表示JavaBean类通过存储器导出一个属性 //从bw中获取propertyName对应的PropertyDescriptor PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is a unsatisfied, non-simple property. // 不要尝试按类型自动装配对象:永远是有意义的,即使它在技术上是一个不满意,复杂属性 //如果pd的属性值类型不是 Object if (Object.class != pd.getPropertyType()) { //获取pd属性的Setter方法的方法参数包装对象 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. // 在有优先级的后处理程序的情况下,不允许急于初始化来进行类型匹配。 //PriorityOrdered:PriorityOrdered是个接口,继承自Ordered接口,未定义任何方法 // -- 若对象o1是Ordered接口类型,o2是PriorityOrdered接口类型,那么o2的优先级高于o1 // -- 若对象o1是PriorityOrdered接口类型,o2是Ordered接口类型,那么o1的优先级高于o2 // -- 其他情况,若两者都是Ordered接口类型或两者都是PriorityOrdered接口类型,调用Ordered接口的getOrder方法得到order值,order值越大,优先级越小 //判断bean对象是否是PriorityOrder实例,如果不是就允许急于初始化来进行类型匹配。 //eger为true时会导致初始化lazy-init单例和由FactoryBeans(或带有"factory-bean"引用的工厂方法)创建 的对象以进行类型检查 boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance()); //AutowireByTypeDependencyDescriptor:根据类型依赖自动注入的描述符,重写了 getDependencyName() 方法,使其永远返回null //将 methodParam 封装包装成AutowireByTypeDependencyDescriptor对象 DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); //根据据desc的依赖类型解析出与descriptor所包装的对象匹配的候选Bean对象 Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); //如果autowiredArgument不为null if (autowiredArgument != null) { //将proeprtyName.autowireArgument作为键值添加到pvs中 pvs.add(propertyName, autowiredArgument); } //遍历所有候选Bean名集合 for (String autowiredBeanName : autowiredBeanNames) { //注册beanName与dependentBeanNamed的依赖关系 registerDependentBean(autowiredBeanName, beanName); //打印跟踪日志 if (logger.isTraceEnabled()) { // 通过属性类型自动装配从bean名'beanName'的属性名'propertyName',bean名为'autowiredBeanName' logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } //将候选Bean名集合情况 autowiredBeanNames.clear(); } } catch (BeansException ex) { //捕捉自动装配时抛出的Bean异常,重新抛出 不满足依赖异常 throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } } /** * <p>获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组</p> * Return an array of non-simple bean properties that are unsatisfied. * These are probably unsatisfied references to other beans in the * factory. Does not include simple properties like primitives or Strings. * <p>返回一个不满足要求的非简单bean属性数组。这些可能是对工厂中其他bean的不满意的引用。不包括简单属性, * 如原始或字符串</p> * @param mbd the merged bean definition the bean was created with * -- 创建bean时适用的合并BeanDefinition * @param bw the BeanWrapper the bean was created with * -- 创建bean时使用的bean保证其 * @return an array of bean property names -- bean属性名数组 * @see org.springframework.beans.BeanUtils#isSimpleProperty */ protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { //TreeSet:TreeSet底层是二叉树,可以对对象元素进行排序,但是自定义类需要实现comparable接口,重写comparaTo()方法。 Set<String> result = new TreeSet<>(); //获取mdbd的所有属性值 PropertyValues pvs = mbd.getPropertyValues(); //PropertyDescriptor:表示JavaBean类通过存储器导出一个属性 //获取bw的所有属性描述对象 PropertyDescriptor[] pds = bw.getPropertyDescriptors(); //遍历属性描述对象 for (PropertyDescriptor pd : pds) { //如果 pd有写入属性方法 && 该pd不是被排除在依赖项检查之外 && pvs没有该pd的属性名 && pd的属性类型不是"简单值类型" if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) && !BeanUtils.isSimpleProperty(pd.getPropertyType())) { //将pdd的属性名添加到result中 result.add(pd.getName()); } } //将result装换成数组 return StringUtils.toStringArray(result); } /** * Extract a filtered set of PropertyDescriptors from the given BeanWrapper, * excluding ignored dependency types or properties defined on ignored dependency interfaces. * <p>从给定的BeanWrapper提取一组经过筛选的PropertyDesciptor,排除忽略的依赖项或忽略项上的定义的属性</p> * @param bw the BeanWrapper the bean was created with -- 创建bean时使用的 bean包装器 * @param cache whether to cache filtered PropertyDescriptors for the given bean Class * -- 是否缓存过滤PropertyDescriptors bean 类 * @return the filtered PropertyDescriptors -- 过滤后的PropertyDesciptors * @see #isExcludedFromDependencyCheck * @see #filterPropertyDescriptorsForDependencyCheck(org.springframework.beans.BeanWrapper) */ protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) { //PropertyDescriptor类表示JavaBean类通过存储器导出一个属性 PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass()); if (filtered == null) { //从bw提取一组经过筛选的propertyDesciptor,排除忽略的依赖项类型或在忽略的依赖项接口上定义的属性。 filtered = filterPropertyDescriptorsForDependencyCheck(bw); //如果需要缓存 if (cache) { //putIfAbsent:如果map集合中没有该key对应的值,则直接添加,并返回null;如果已经存在对应的值,则依旧为原来的值.并返回原来的值 //将bw的bean实例的类型,filted添加到filteredPropertyDescriptorsCache中 PropertyDescriptor[] existing = this.filteredPropertyDescriptorsCache.putIfAbsent(bw.getWrappedClass(), filtered); //如果已经存在对应的值 if (existing != null) { //引用存在对应的值,正常来说不会出现这钟情况,因为已经存在的情况, // -- 已经由该方法的第一行过滤掉了,除非出现并发调用该方法的情况,这个时候永远都会返回第一次的值, // -- 以保证在并发的情况下,返回的对象永远都是同一个对象 filtered = existing; } } } return filtered; } /** * Extract a filtered set of PropertyDescriptors from the given BeanWrapper, * excluding ignored dependency types or properties defined on ignored dependency interfaces. * <p>从给定的BeanWrapper提取一组经过筛选的propertyDesciptor,排除忽略的依赖项类型或在忽略的依赖项接口上定义的属性。</p> * @param bw the beanwrapper the bean was created with * -- 创建bean时使用的 bean 包装器 * @return the filtered PropertyDescriptors -- 过滤后的PropertyDesciptors * @see #isExcludedFromDependencyCheck */ protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) { //使用List包装bw的PropertyDesciptors元素 List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors())); // 删除 pds 中 由CGLIB定义的属性和类型与被忽略项的依赖类型匹配的属性,或者由被忽略的依赖接口定义的PropertyDescriptor pds.removeIf(this::isExcludedFromDependencyCheck); //将pds转换成数组 return pds.toArray(new PropertyDescriptor[0]); } /** * Determine whether the given bean property is excluded from dependency checks. * <p>确定给定bean属性是否被排除在依赖项检查之外</p> * <p>This implementation excludes properties defined by CGLIB and * properties whose type matches an ignored dependency type or which * are defined by an ignored dependency interface. * <p>此实现排除了由CGLIB定义的属性和类型与被忽略项的依赖类型匹配的属性,或者由被忽略 * 的依赖接口定义的属性</p> * @param pd the PropertyDescriptor of the bean property * --- bean 属性的 PropertyDescriptor * @return whether the bean property is excluded -- bean属性是否被排除 * @see #ignoreDependencyType(Class) * @see #ignoreDependencyInterface(Class) */ protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) { //pd的属性是CGLIB定义的属性 || 该工厂的忽略依赖类型列表中包含该pd的属性类型 || pd的属性是ignoredDependencyInterfaces里面的接口定义的方法 return (AutowireUtils.isExcludedFromDependencyCheck(pd) || this.ignoredDependencyTypes.contains(pd.getPropertyType()) || AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces)); } /** * <p>检查依赖项:主要检查pd的setter方法需要赋值时,pvs中有没有满足其pd的需求的属性值可供其赋值。</p> * Perform a dependency check that all properties exposed have been set, * if desired. Dependency checks can be objects (collaborating beans), * simple (primitives and String), or all (both). * <p>如果需要,执行依赖项检查,以确定已设置了公开的所有属性。依赖项检查可以是对像(协作bean), * 简单(原语和字符串)或全部(两者都有)</p> * @param beanName the name of the bean -- bean名 * @param mbd the merged bean definition the bean was created with * -- 合并后的BeanDefinition的bean创建 * @param pds the relevant property descriptors for the target bean * -- 相关的目标bean的属性描述符 * @param pvs the property values to be applied to the bean * -- 适合的bean属性值 * @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor) */ protected void checkDependencies( String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs) throws UnsatisfiedDependencyException { //获取mbd的依赖检查代码,默认为DEPENDENCY_CHECK_NONE,不检查 int dependencyCheck = mbd.getDependencyCheck(); //遍历pds for (PropertyDescriptor pd : pds) { //如果pd有setter方法 && (pvs为null || pvs没有pd的属性名的PropertyValue) if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) { //simlpeProperty:其属性类型为 primitive 或者 primitive包装器,枚举,字符串, 或 其他字符,数字,日期,时态,URI,URL,语言环境或类 //如果pd的属性类型是"简单"类型 boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType()); // 是否不满足: (dependencyCheck为对所有属性检查) || (pd的属性类型是"简单"类型 && dependencyCheck为 对原始类型(基本类型,String,集合)检查) // -- || (pd的属性类型不是"简单"类型 && 对依赖对象检查) boolean unsatisfied = (dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_ALL) || (isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE) || (!isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS); //如果不满足 if (unsatisfied) { //这个时候意味着 pd的setter方法是需要赋值,但是pvs中没有满足其pd的需求的属性值进行赋值 //抛出不满足依赖异常:设置此属性值或禁用此bean依赖项检查 throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(), "Set this property value or disable dependency checking for this bean."); } } } } /** * Apply the given property values, resolving any runtime references * to other beans in this bean factory. Must use deep copy, so we * don't permanently modify this property. * <p>应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 * 不会永久地修改这个属性</p> * @param beanName the bean name passed for better exception information * -- 传递bean名以获得更好的异常信息 * @param mbd the merged bean definition * -- 合并后的bean定义 * @param bw the BeanWrapper wrapping the target object * -- 包装目标对象的BeanWrapper * @param pvs the new property values * -- 新得属性值 */ protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { //如果pvs没有PropertyValue if (pvs.isEmpty()) { //直接结束方法 return; } //如果有安全管理器 且 bw是BeanWrapperImpld恶实例 if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { //设置bw的安全上下文为工厂的访问控制上下文 ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } //MutablePropertyValues:PropertyValues接口的默认实现。允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造 MutablePropertyValues mpvs = null; //原始属性值列表 List<PropertyValue> original; //如果pvs是MutablePropertyValues实例 if (pvs instanceof MutablePropertyValues) { //将pvs强转为MutablePropertyValue实例 mpvs = (MutablePropertyValues) pvs; //isConverted:返回该holder是否只包含转换后的值(true),或者是否仍然需要转换这些值 //如果mpvs只包含转换后的值 if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. // 快捷方式:使用 pre-conveted初始值 try { //使用mpvs批量设置bw包装的Bean对象属性 bw.setPropertyValues(mpvs); //终止方法。 return; } catch (BeansException ex) { //捕捉Bean异常,重新抛出Bean创佳异常:错误设置属性值。 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } //获取mpvs的PropertyValue对象列表 original = mpvs.getPropertyValueList(); } else { //获取pvs的PropertyValue对象数组,并将其转换成列表 original = Arrays.asList(pvs.getPropertyValues()); } //获取工厂的自定义类型转换器 TypeConverter converter = getCustomTypeConverter(); //如果工厂中没有设置自定义类型转换器 if (converter == null) { //使用bw作为转换器 converter = bw; } //BeanDefinitionValueResolver:在bean工厂实现中使用Helper类,它将beanDefinition对象中包含的值解析为应用于 目标bean实例的实际值 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); // Create a deep copy, resolving any references for values. // 创建一个深拷贝,解析任何值引用 List<PropertyValue> deepCopy = new ArrayList<>(original.size()); //是否还需要解析标记 boolean resolveNecessary = false; //遍历orgininal for (PropertyValue pv : original) { //如果pv已经是转换后的值 if (pv.isConverted()) { //将pv添加到deepCopy中 deepCopy.add(pv); } else {//pv需要转换值 //获取pv的属性名 String propertyName = pv.getName(); //获取pv的原始属性值 Object originalValue = pv.getValue(); //AutowiredPropertyMarker.INSTANCE:自动生成标记的规范实例 if (originalValue == AutowiredPropertyMarker.INSTANCE) { //获取propertyName在bw中的setter方法 Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod(); //如果setter方法为null if (writeMethod == null) { //抛出非法参数异常:自动装配标记属性没有写方法。 throw new IllegalArgumentException("Autowire marker for property without write method: " + pv); } //将writerMethod封装到DependencyDescriptor对象 originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true); } //交由valueResolver根据pv解析出originalValue所封装的对象 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); //默认转换后的值是刚解析出来的值 Object convertedValue = resolvedValue; //可转换标记: propertyName是否bw中的可写属性 && prepertyName不是表示索引属性或嵌套属性(如果propertyName中有'.'||'['就认为是索引属性或嵌套属性) boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); //如果可转换 if (convertible) { //将resolvedValue转换为指定的目标属性对象 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); } // Possibly store converted value in merged bean definition, // in order to avoid re-conversion for every created bean instance. // 可以将转换后的值存储合并后BeanDefinition中,以避免对每个创建的Bean实例进行重新转换 //如果resolvedValue与originalValue是同一个对象 if (resolvedValue == originalValue) { //如果可转换 if (convertible) { //将convertedValue设置到pv中 pv.setConvertedValue(convertedValue); } //将pv添加到deepCopy中 deepCopy.add(pv); } //TypedStringValue:类型字符串的Holder,这个holder将只存储字符串值和目标类型。实际得转换将由Bean工厂执行 //如果可转换 && originalValue是TypedStringValue的实例 && orginalValue不是标记为动态【即不是一个表达式】&& // convertedValue不是Collection对象 或 数组 else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) { //将convertedValue设置到pv中 pv.setConvertedValue(convertedValue); //将pv添加到deepCopy中 deepCopy.add(pv); } else { //标记还需要解析 resolveNecessary = true; //根据pv,convertedValue构建PropertyValue对象,并添加到deepCopy中 deepCopy.add(new PropertyValue(pv, convertedValue)); } } } //mpvs不为null && 已经不需要解析 if (mpvs != null && !resolveNecessary) { //将此holder标记为只包含转换后的值 mpvs.setConverted(); } // Set our (possibly massaged) deep copy. // 设置我们的深层拷贝(可能时按摩过的) try { //按原样使用deepCopy构造一个新的MutablePropertyValues对象然后设置到bw中以对bw的属性值更新 bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) {//捕捉更新属性值的Bean异常 //重新抛出Bean创建异常:错误设置属性值 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } /** * Convert the given value for the specified target property. * <p>给定的值转换为指定的目标属性对象</p> * @param value */ @Nullable private Object convertForProperty( @Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) { //如果coverter是BeanWrapperImpl实例 if (converter instanceof BeanWrapperImpl) { return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName); } else { //获取 propertyName的属性描述符对象 PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); //获取pd的setter方法参数 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); //将value转换为pd要求的属性类型对象 return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam); } } /** * Initialize the given bean instance, applying factory callbacks * as well as init methods and bean post processors. * <p>初始化给定的Bean实例,应用工厂回调以及init方法和BeanPostProcessors</p> * <p>Called from {@link #createBean} for traditionally defined beans, * and from {@link #initializeBean} for existing bean instances. * <p>对于传统定义的Bean,从createBean调用;对于现有的Bean实例,从initalizeBean调用</p> * @param beanName the bean name in the factory (for debugging purposes) * -- 工厂中的Bean名称(用于调试) * @param bean the new bean instance we may need to initialize * -- 我们可能需要初始化的新Bean实例 * @param mbd the bean definition that the bean was created with * (can also be {@code null}, if given an existing bean instance) * -- 创建Bean时使用的BeanDefinition(如果给定现有的Bean实例,也可以为null) * @return the initialized bean instance (potentially wrapped) * -- 初始化的Bean实例(可能已包装) * @see BeanNameAware * @see BeanClassLoaderAware * @see BeanFactoryAware * @see #applyBeanPostProcessorsBeforeInitialization * @see #invokeInitMethods * @see #applyBeanPostProcessorsAfterInitialization */ protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { //如果安全管理器不为null if (System.getSecurityManager() != null) { //以特权的方式执行 回调 bean 中 Aware接口 方法 AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { //回调 bean 中 Aware接口 方法 invokeAwareMethods(beanName, bean); } //初始化 包装后的Bean 为 bean Object wrappedBean = bean; //如果mdb不为null || mbd不是"synthetic"。一般是指只有AOP相关的prointCut配置或者Advice配置才会将 synthetic设置为true if (mbd == null || !mbd.isSynthetic()) { //将BeanPostProcessors应用到给定的现有Bean实例,调用它们的postProcessBeforeInitialization初始化 方法。 // -- 返回的Bean实例可能是原始Bean包装器 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { //调用初始化方法,先调用bean的InitializingBean接口方法,后调用bean的自定义初始化方法 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { //捕捉调用初始化方法时抛出的异常,重新抛出Bean创建异常:调用初始化方法失败 throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } //如果mbd为null || mbd不是"synthetic"。一般是指只有AOP相关的prointCut配置或者Advice配置才会将 synthetic设置为true if (mbd == null || !mbd.isSynthetic()) { //将BeanPostProcessors应用到给定的现有Bean实例,调用它们的postProcessAfterInitialization方法。 // -- 返回的Bean实例可能是原始Bean包装器 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } //返回包装后的Bean return wrappedBean; } /** * 回调 bean 中 Aware接口 方法 * @param beanName bean名 * @param bean 当前Bean对象 */ private void invokeAwareMethods(final String beanName, final Object bean) { //如果 bean 是 Aware 实例 if (bean instanceof Aware) { //如果bean是BeanNameAware实例 if (bean instanceof BeanNameAware) { //调用 bean 的setBeanName方法 ((BeanNameAware) bean).setBeanName(beanName); } //如果bean是 BeanClassLoaderAware 实例 if (bean instanceof BeanClassLoaderAware) { //获取此工厂的类加载器以加载Bean类(即使无法使用系统ClassLoader,也只能为null) ClassLoader bcl = getBeanClassLoader(); if (bcl != null) { //调用 bean 的 setBeanClassLoader 方法 ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl); } } //如果bean是 BeanFactoryAware 实例 if (bean instanceof BeanFactoryAware) { //调用 bean 的 setBeanFactory 方法。 ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } } /** * <p>调用初始化方法,先调用bean的InitializingBean接口方法,后调用bean的自定义初始化方法</p> * Give a bean a chance to react now all its properties are set, * and a chance to know about its owning bean factory (this object). * This means checking whether the bean implements InitializingBean or defines * a custom init method, and invoking the necessary callback(s) if it does. * <p>现在让Bean有机会对它所有的属性进行反应,并有机会了解它所拥有的Bean工厂(这个对象)。 * 这意味着检查Bean是否实现了InitalizingBean或定义了一个自定以init方法,如果实现了,则 * 调用必要的回调</p> * @param beanName the bean name in the factory (for debugging purposes) * -- 工厂中的Bean名(用于调试) * @param bean the new bean instance we may need to initialize * -- 我们可能需要初始化的新Bean实例 * @param mbd the merged bean definition that the bean was created with * (can also be {@code null}, if given an existing bean instance) * -- 创建Bean时使用的合并BeanDefinition(如果给定现有Bean实例,也可以为null) * @throws Throwable if thrown by init methods or by the invocation process * -- 如果由init方法或调用进程抛出 * @see #invokeCustomInitMethod */ protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { //InitialziingBean:当Bean的所有属性都被BeanFactory设置好后,Bean需要执行相应的接口:例如执行自定义 初始化,或者仅仅是检查所有强制属性是否已经设置好。 //bean是InitializingBean实例标记 boolean isInitializingBean = (bean instanceof InitializingBean); //isExternallyManagedInitMethod是否外部受管理的Init方法名 //如果 bean是InitializingBean实例 && (mdb为null || 'afterPropertiesSet' 不是外部受管理的Init方法名) if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { //如果是日志级别为跟踪模式 if (logger.isTraceEnabled()) { //跟踪日志:在具体名称的Bean上调用 afterPrpertiesSet() logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } //如果安全管理器不为null if (System.getSecurityManager() != null) { try { //以特权方式调用 bean的 afterPropertiesSet 方法 AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> { ((InitializingBean) bean).afterPropertiesSet(); return null; }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { //调用 bean的 afterPropertiesSet 方法 ((InitializingBean) bean).afterPropertiesSet(); } } //如果mbd不为null && bean不是 NullBean类 if (mbd != null && bean.getClass() != NullBean.class) { //获取mbd指定的初始化方法名 String initMethodName = mbd.getInitMethodName(); //如果initMethodName不为null && (bean不是InitializingBean实例 && 'afterPropertiesSet'是初始化方法名) // && initMethodName不是外部受管理的Init方法名 if (StringUtils.hasLength(initMethodName) && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { //在bean上调用指定的自定义init方法 invokeCustomInitMethod(beanName, bean, mbd); } } } /** * Invoke the specified custom init method on the given bean. * Called by invokeInitMethods. * <p>在给定的Bean上调用指定的自定义init方法</p> * <p>Can be overridden in subclasses for custom resolution of init * methods with arguments. * <p>可以在子类中覆盖初始化方法的自定义解析</p> * @see #invokeInitMethods */ protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { //获取mbd的初始化方法名 String initMethodName = mbd.getInitMethodName(); //如果initMethodName为null,抛出异常 Assert.state(initMethodName != null, "No init method set"); // BeanUtils.findMethod(bean.getClass(), initMethodName):找到一个具有给定方法名和给定参数类型的方法,该方法在给定 // 类或其父类中声明。首选 公共方法,但也将返回受保护的包访问或私有方法。 // ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)):确定给定的类是否具有带有给定签名的公共方法, // 并返回(如果可用)(否则返回null). //根据mbd是否允许访问非公共构造函数和方法的权限获取初始化方法对象 Method initMethod = (mbd.isNonPublicAccessAllowed() ? BeanUtils.findMethod(bean.getClass(), initMethodName) : ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName)); //如果初始化方法为null if (initMethod == null) { //如 mbd 指示配置的init方法为默认方法,一般指定的初始化方法名 isEnforceInitMethod() 就会为true if (mbd.isEnforceInitMethod()) { //抛出 BeanDefinition非法异常:无法找到名为'initMethodName'的初始化方法在bean名为'beanName'中 throw new BeanDefinitionValidationException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'"); } else { //如果当前日志级别为跟踪 if (logger.isTraceEnabled()) { //打印跟踪日志:没有名为'initMethodName'默认初始化方法在名为'beanName'中找到 logger.trace("No default init method named '" + initMethodName + "' found on bean with name '" + beanName + "'"); } // Ignore non-existent default lifecycle methods. // 忽略不存在的默认生命周期方法 return; } } //如果当前日志级别为跟踪 if (logger.isTraceEnabled()) { //调用名为'initMethodName'默认初始化方法在名为'beanName'中 logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'"); } //获取method相应的接口方法对象,如果找不到,则返回原始方法 Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod); //如果有安全管理器 if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { //以特权方式 使 methodToInvoke 可访问,在需要时设置它的可访问性 ReflectionUtils.makeAccessible(methodToInvoke); return null; }); try { //以特权的方式 调用 bean的methodToInvoke方法 AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> methodToInvoke.invoke(bean), getAccessControlContext()); } catch (PrivilegedActionException pae) { //InvocationTargetException:当被调用的方法的内部抛出了异常而没有被捕获时,将由此异常接收!!! InvocationTargetException ex = (InvocationTargetException) pae.getException(); //获取其目标异常,重新抛出 throw ex.getTargetException(); } } else { try { // methodToInvoke 可访问,在需要时设置它的可访问性 ReflectionUtils.makeAccessible(methodToInvoke); //调用 bean的methodToInvoke方法 methodToInvoke.invoke(bean); } catch (InvocationTargetException ex) { //InvocationTargetException:当被调用的方法的内部抛出了异常而没有被捕获时,将由此异常接收!!! //获取其目标异常,重新抛出 throw ex.getTargetException(); } } } /** * Applies the {@code postProcessAfterInitialization} callback of all * registered BeanPostProcessors, giving them a chance to post-process the * object obtained from FactoryBeans (for example, to auto-proxy them). * <p>应用所有已注册BeanPostProcessor的postProcessAfterInitalization回调,使它 * 们有机会对FactoryBeans获得的对象进行后处理(例如,自动代理它们)</p> * @see #applyBeanPostProcessorsAfterInitialization */ @Override protected Object postProcessObjectFromFactoryBean(Object object, String beanName) { //初始化后的后处理 return applyBeanPostProcessorsAfterInitialization(object, beanName); } /** * Overridden to clear FactoryBean instance cache as well. * <p>也被重新以清除FactoryBean实例缓存</p> */ @Override protected void removeSingleton(String beanName) { //获取单例互斥体,一般使用singletonObjects synchronized (getSingletonMutex()) { //1. 从该工厂单例缓存中删除具有给定名称的Bean。如果创建失败,则能够清理饿汉式注册 的单例 //2. 重写以清除FactoryBean对象缓存 super.removeSingleton(beanName); //factoryBeanInstanceCache:未完成的FactoryBean实例的高速缓存 //删除beanName对应的factoryBean对象 this.factoryBeanInstanceCache.remove(beanName); } } /** * Overridden to clear FactoryBean instance cache as well. */ @Override protected void clearSingletonCache() { synchronized (getSingletonMutex()) { super.clearSingletonCache(); this.factoryBeanInstanceCache.clear(); } } /** * Expose the logger to collaborating delegates. * @since 5.0.7 */ Log getLogger() { return logger; } /** * <p>根据类型依赖自动注入的描述符,重写了 {@link #getDependencyName()} 方法,使其永远返回null</p> * Special DependencyDescriptor variant for Spring's good old autowire="byType" mode. * Always optional; never considering the parameter name for choosing a primary candidate. * <p>Spring 古老的 autowire = 'byType' 模式的特殊依赖描述符变体。总是可选;在选择主要候选对象时从不考虑 * 参数名称</p> */ @SuppressWarnings("serial") private static class AutowireByTypeDependencyDescriptor extends DependencyDescriptor { public AutowireByTypeDependencyDescriptor(MethodParameter methodParameter, boolean eager) { super(methodParameter, false, eager); } @Override public String getDependencyName() { return null; } } /** * {@link MethodCallback} used to find {@link FactoryBean} type information. */ private static class FactoryBeanMethodTypeFinder implements MethodCallback { private final String factoryMethodName; private ResolvableType result = ResolvableType.NONE; FactoryBeanMethodTypeFinder(String factoryMethodName) { this.factoryMethodName = factoryMethodName; } @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (isFactoryBeanMethod(method)) { ResolvableType returnType = ResolvableType.forMethodReturnType(method); ResolvableType candidate = returnType.as(FactoryBean.class).getGeneric(); if (this.result == ResolvableType.NONE) { this.result = candidate; } else { Class<?> resolvedResult = this.result.resolve(); Class<?> commonAncestor = ClassUtils.determineCommonAncestor(candidate.resolve(), resolvedResult); if (!ObjectUtils.nullSafeEquals(resolvedResult, commonAncestor)) { this.result = ResolvableType.forClass(commonAncestor); } } } } private boolean isFactoryBeanMethod(Method method) { return (method.getName().equals(this.factoryMethodName) && FactoryBean.class.isAssignableFrom(method.getReturnType())); } ResolvableType getResult() { Class<?> resolved = this.result.resolve(); boolean foundResult = resolved != null && resolved != Object.class; return (foundResult ? this.result : ResolvableType.NONE); } } }
最新回复(0)