/** * Central method of this class: creates a bean instance, * populates the bean instance, applies post-processors, etc. * <p> * 创建bean的核心方法 * * @see #doCreateBean */ @Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } //进行变量的赋值 RootBeanDefinitionmbdToUse= 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. // 1.解析beanName对应的Bean的类型,例如:com.test.spring.dao.UserDao Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { // 如果resolvedClass存在,并且mdb的beanClass类型不是Class,并且mdb的beanClass不为空(则代表beanClass存的是Class的name), // 则使用mdb深拷贝一个新的RootBeanDefinition副本,并且将解析的Class赋值给拷贝的RootBeanDefinition副本的beanClass属性, // 该拷贝副本取代mdb用于后续的操作 mbdToUse = newRootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
/** * Actually create the specified bean. Pre-creation processing has already happened * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks. * <p>Differentiates between default bean instantiation, use of a * factory method, and autowiring a constructor. * 真实的开始创建bean的实例 * 主要更能 * 1、创建bean的实例 * 2、对各种注解进行装配 * 3、实现依赖注入 * */ protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final@Nullable Object[] args) throws BeanCreationException {
// 11.如果允许提前曝光实例,则进行循环依赖检查 if (earlySingletonExposure) { ObjectearlySingletonReference= getSingleton(beanName, false); // 11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空 if (earlySingletonReference != null) { if (exposedObject == bean) { // 11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用 exposedObject = earlySingletonReference;
// 11.3 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例 // && 当前bean有被其他bean依赖 } elseif (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { // 11.4 拿到依赖当前bean的所有bean的beanName数组 String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = newLinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { // 11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { // 11.6 移除失败的添加到 actualDependentBeans actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { // 11.7 如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据” thrownewBeanCurrentlyInCreationException(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."); } } } }
/** * Create a new instance for the specified bean, using an appropriate instantiation strategy: * factory method, constructor autowiring, or simple instantiation. * 创建一个bean的实例 首先factory method的方式,然后选择构造方法创建最后无参创建 */ protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. //反射拿到Class对象,解析bean的类型信息 Class<?> beanClass = resolveBeanClass(mbd, beanName);
// beanClass不为空 && beanClass不是公开类(不是public修饰) && 该bean不允许访问非公共构造函数和方法,则抛异常 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); }
/** * Add the given singleton factory for building the specified singleton * if necessary. * <p>To be called for eager registration of singletons, e.g. to be able to * resolve circular references. * 设置三级缓存 */ protectedvoidaddSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, "Singleton factory must not be null"); synchronized (this.singletonObjects) { // 1.如果beanName不存在于singletonObjects缓存中 //一级缓存不存在beanName if (!this.singletonObjects.containsKey(beanName)) { // 2.将beanName和singletonFactory注册到singletonFactories缓存(beanName -> 该beanName的单例工厂) //设置beanName和匿名类的映射关系加入到三级缓存 this.singletonFactories.put(beanName, singletonFactory); // 3.移除earlySingletonObjects缓存中的beanName(beanName -> beanName的早期单例对象) this.earlySingletonObjects.remove(beanName); // 4.将beanName注册到registeredSingletons缓存(已经注册的单例集合) this.registeredSingletons.add(beanName); } } }
/** * Populate the bean instance in the given BeanWrapper with the property values * from the bean definition. * 依赖注入的核心方法 */ @SuppressWarnings("deprecation")// for postProcessPropertyValues protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // 2.bw为空时的处理 if (bw == null) { if (mbd.hasPropertyValues()) { // 2.1 如果bw为空,属性不为空,抛异常,无法将属性值应用于null实例 thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 2.2 如果bw为空,属性也为空,则跳过 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. // 用于标识是否继续之后的属性填充 //这里很有意思,写接口可以让所有类都不能依赖注入 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { // 3.1 如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历处理InstantiationAwareBeanPostProcessor for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessoribp= (InstantiationAwareBeanPostProcessor) bp; // 3.2 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { // 3.3 如果返回false,将continueWithPropertyPopulation赋值为false,代表要跳过之后的属性填充 //是否需要DI,依赖注入不需要直接返回 return; } } } }
/** * Fill in any missing property values with references to * other beans in this factory if autowire is set to "byName". * 是根据属性名称完成自动依赖注入的 */ protectedvoidautowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 1.寻找bw中需要依赖注入的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { // 2.校验是否存在beanName=propertyName的bean实例或者BeanDefinition if (containsBean(propertyName)) { // 3.获取propertyName的bean实例对象 Objectbean= getBean(propertyName); // 4.将属性名和属性值添加到pvs pvs.add(propertyName, bean); // 5.注册依赖关系到缓存(beanName依赖propertyName) registerDependentBean(propertyName, beanName); if (logger.isTraceEnabled()) { logger.trace("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
/** * Register a dependent bean for the given bean, * to be destroyed before the given bean is destroyed. * 注册依赖的bean和bean name的映射关系 * * @param beanName the name of the bean * @param dependentBeanName the name of the dependent bean */ publicvoidregisterDependentBean(String beanName, String dependentBeanName) { // 1.解析别名 StringcanonicalName= canonicalName(beanName);
/** * Abstract method defining "autowire by type" (bean properties by type) behavior. * <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. * 按类型注入 */ protectedvoidautowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获取 TypeConverter 实例 // 使用自定义的 TypeConverter,用于取代默认的 PropertyEditor 机制 TypeConverterconverter= getCustomTypeConverter(); if (converter == null) { converter = bw; } //创建BeanName属性名称集合 Set<String> autowiredBeanNames = newLinkedHashSet<>(4); // 1.寻找bw中需要依赖注入的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); // 2.遍历所有需要依赖注入的属性 for (String propertyName : propertyNames) { try { PropertyDescriptorpd= 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. if (Object.class != pd.getPropertyType()) { // 3.获取指定属性的set方法,封装成MethodParameter(必须有set方法才能通过属性来注入) MethodParametermethodParam= BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. //如果后置处理器有优先级,则不允许eager init进行类型匹配。 booleaneager= !(bw.getWrappedInstance() instanceof PriorityOrdered); // 4.将MethodParameter的方法参数索引信息封装成DependencyDescriptor DependencyDescriptordesc=newAutowireByTypeDependencyDescriptor(methodParam, eager); // 5.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中 // 当属性存在过个封装 bean 时将会找到所有匹配的 bean 并将其注入 ObjectautowiredArgument= resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { // 6.如果找到了依赖的bean实例,将属性名和bean实例放到pvs中 pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { // 7.注册依赖关系,beanName依赖autowiredBeanName registerDependentBean(autowiredBeanName, beanName); if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } //8.清空属性名称集合 autowiredBeanNames.clear(); } } catch (BeansException ex) { thrownewUnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }
/** * 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. * 将所有PropertyValues中的属性填充到bean中 */ protectedvoidapplyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { if (pvs.isEmpty()) { return; }