spring源码学习 - 一个简单bean的实例化过程

前言

在Spring容器中bean的解析注册和实例化是两个不同的过程,上一篇讲到Spring在初始化的时候会将我们定义的javaBean的相关元信息封装到beanDefinitionMap当中. 当要使用这个javaBean的时候spring会根据beanDefinition来实例化该对象.对初始化过程不是很清楚的朋友推荐先看看这两篇文章了解下解析注册过程

  • spring源码学习 - xml方式bean的解析注册过程
  • spring源码学习 - 注解bean的解析注册过程
带着问题看源码:

如果不new对象, spring是如何实例化对象的

debug过程,这里拿一个最简单的javaBean
  1. 创建一个简单的javaBean
public class TestBean {
    private String name;

    public TestBean() {
    }

    public TestBean(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  1. 在spring.xml中配置
    
        
    
  1. 准备测试环境,这里采用spring提供的web单元测试功能,对spring测试功能的不清楚的朋友可以看下文档.
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "classpath:src/main/webapp")
@ContextConfiguration({"classpath:spring.xml", "classpath:spring/spring-mvc.xml"})
@Transactional
public class DebugSpring {
    private static final Logger log = LoggerFactory.getLogger(DebugSpring.class);

    @Test
    public void testLoad() throws IOException {
        Resource resource = new ClassPathResource("spring.xml");
        BeanFactory xmlBeanFactory = new XmlBeanFactory(resource);
        TestBean testBean = xmlBeanFactory.getBean("testBean", TestBean.class); 
        log.debug("test bean name is :{}", testBean.getName());
    }
}
  1. 测试环境准备好了,在TestBean testBean = xmlBeanFactory.getBean("testBean", TestBean.class);打断点开始进行正式的debug过程,进入到:

AbstractBeanFactory

@Override
 public  T getBean(String name, Class requiredType) throws BeansException {
     return doGetBean(name, requiredType, null, false);
 }

 @SuppressWarnings("unchecked")
 protected  T doGetBean(
         final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
         throws BeansException {
     //获取真实的beanName
     // 分两种情况需要转换
     // 1.别名
     // 2.传入的是工厂Bean名, 例如:"&beanName"
     final String beanName = transformedBeanName(name);
     Object bean;
     // Eagerly check singleton cache for manually registered singletons.
     //如果我们获取的bean的scope是singleton的话,首先实例化bean的时候spring会将其缓存起来,提升性能
     Object sharedInstance = getSingleton(beanName);
     //这里获取到的sharedInstance的对象还处于最初始状态的bean
     if (sharedInstance != null && args == null) {
         if (logger.isDebugEnabled()) {
             if (isSingletonCurrentlyInCreation(beanName)) {
                 logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                         "' that is not fully initialized yet - a consequence of a circular reference");
             }
             else {
                 logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
             }
         }
         //我们真正需要的bean是从工厂bean中定义的factory-method方法中生产的bean
         bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
     }
     //如果是第一次创建该bean
     else {
         //原型模式下是无法解决循环依赖的,直接抛异常
         //a中有b的属性,b中有a属性
         //当创建a时会去创建b,创建b时会去创建a直接就死循环了....
         if (isPrototypeCurrentlyInCreation(beanName)) {
             throw new BeanCurrentlyInCreationException(beanName);
         }
         //尝试从父容器中进行加载
         BeanFactory parentBeanFactory = getParentBeanFactory();
         //如果当前容器属于子容器,并且该容器中没有定义该bean则从父类中进行加载
         //一直递归下去
         if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
             // Not found -> check parent.
             String nameToLookup = originalBeanName(name);
             if (args != null) {
                 // Delegation to parent with explicit args.
                 return (T) parentBeanFactory.getBean(nameToLookup, args);
             }
             else {
                 // No args -> delegate to standard getBean method.
                 return parentBeanFactory.getBean(nameToLookup, requiredType);
             }
         }
         //如果是创建bean则进行相应记录
         if (!typeCheckOnly) {
             markBeanAsCreated(beanName);
         }

         try {
             final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
             checkMergedBeanDefinition(mbd, beanName, args);

             //如果该bean中存在依赖bean
             String[] dependsOn = mbd.getDependsOn();
             if (dependsOn != null) {
                 for (String dependsOnBean : dependsOn) {
                     if (isDependent(beanName, dependsOnBean)) {
                         throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                 "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
                     }
                     //注册
                     registerDependentBean(dependsOnBean, beanName);
                     //依赖bean中可能还存在依赖bean,进入递归
                     getBean(dependsOnBean);
                 }
             }

             // 作用域是单例模式,当依赖bean创建完成,开始创建本身实例
             if (mbd.isSingleton()) {
                 //首先创建工厂bean
                 //然后由工厂bean创建真实bean对象
                 sharedInstance = getSingleton(beanName, new ObjectFactory() {
                     @Override
                     public Object getObject() throws BeansException {
                         try {
                             return createBean(beanName, mbd, args);
                         }
                         catch (BeansException ex) {
                             // Explicitly remove instance from singleton cache: It might have been put there
                             // eagerly by the creation process, to allow for circular reference resolution.
                             // Also remove any beans that received a temporary reference to the bean.
                             destroySingleton(beanName);
                             throw ex;
                         }
                     }
                 });
                 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
             }
             //原型模式
             else if (mbd.isPrototype()) {
                 // It's a prototype -> create a new instance.
                 Object prototypeInstance = null;
                 try {
                     beforePrototypeCreation(beanName);
                     prototypeInstance = createBean(beanName, mbd, args);
                 }
                 finally {
                     afterPrototypeCreation(beanName);
                 }
                 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
             }
             //自定义作用域
             else {
                 String scopeName = mbd.getScope();
                 final Scope scope = this.scopes.get(scopeName);
                 if (scope == null) {
                     throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                 }
                 try {
                     Object scopedInstance = scope.get(beanName, new ObjectFactory() {
                         @Override
                         public Object getObject() throws BeansException {
                             beforePrototypeCreation(beanName);
                             try {
                                 return createBean(beanName, mbd, args);
                             }
                             finally {
                                 afterPrototypeCreation(beanName);
                             }
                         }
                     });
                     bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                 }
                 catch (IllegalStateException ex) {
                     throw new BeanCreationException(beanName,
                             "Scope '" + scopeName + "' is not active for the current thread; consider " +
                             "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                             ex);
                 }
             }
         }
         catch (BeansException ex) {
             cleanupAfterBeanCreationFailure(beanName);
             throw ex;
         }
     }

     // 校验实例是否是我们需要的类型类型
     if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
         try {
             return getTypeConverter().convertIfNecessary(bean, requiredType);
         }
         catch (TypeMismatchException ex) {
             if (logger.isDebugEnabled()) {
                 logger.debug("Failed to convert bean '" + name + "' to required type [" +
                         ClassUtils.getQualifiedName(requiredType) + "]", ex);
             }
             throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
         }
     }
     return (T) bean;
 }
 
 
  1. 看下从缓存中获取bean实例过程,进入

DefaultSingletonBeanRegistry

  protected Object getSingleton(String beanName, boolean allowEarlyReference) {
      Object singletonObject = this.singletonObjects.get(beanName);
      //如果缓存中为空,并且该bean正在被创建
      //这里需要说明下为什么存在bean正在被创建的情况呢?
      //答案是循环依赖,spring解决单例模式循环依赖问题的方法是提前曝光,意思是假设检测到了循环依赖的话
      //spring会将循环依赖的对象提前创建好,到使用的时候直接获取就好.
      if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
          //全局锁
          synchronized (this.singletonObjects) {
              singletonObject = this.earlySingletonObjects.get(beanName);
              //如果bean正在被加载则不进行处理
              if (singletonObject == null && allowEarlyReference) {
                  //获取工厂bean实例
                  ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
                  if (singletonFactory != null) {
                      //调用工厂bean生产我们需要的bean实例
                      singletonObject = singletonFactory.getObject();
                      this.earlySingletonObjects.put(beanName, singletonObject);
                      this.singletonFactories.remove(beanName);
                  }
              }
          }
      }
      return (singletonObject != NULL_OBJECT ? singletonObject : null);
  }

AbstractBeanFactory

```
protected Object getObjectForBeanInstance(
        Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {

    // 校验
    if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
        throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
    }

    //如果我们获取的是factory工厂bean的话就直接返回
    if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
        return beanInstance;
    }
    //如果我们要获取的是正常的bean,这里beanInstance类型是factoryBean
    Object object = null;
    if (mbd == null) {
        //尝试从缓存中加载
        object = getCachedObjectForFactoryBean(beanName);
    }
    if (object == null) {
        // Return bean instance from factory.
        FactoryBean factory = (FactoryBean) beanInstance;
        // Caches object obtained from FactoryBean if it is a singleton.
        if (mbd == null && containsBeanDefinition(beanName)) {
            mbd = getMergedLocalBeanDefinition(beanName);
        }
        boolean synthetic = (mbd != null && mbd.isSynthetic());
        //实力化bean
        object = getObjectFromFactoryBean(factory, beanName, !synthetic);
    }
    return object;
}

 > FactoryBeanRegistrySupport

protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName, boolean shouldPostProcess) {
    if (factory.isSingleton() && containsSingleton(beanName)) {
        synchronized (getSingletonMutex()) {
            Object object = this.factoryBeanObjectCache.get(beanName);
            if (object == null) {
                //继续进入这里
                object = doGetObjectFromFactoryBean(factory, beanName);
                // Only post-process and store if not put there already during getObject() call above
                // (e.g. because of circular reference processing triggered by custom getBean calls)
                Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
                if (alreadyThere != null) {
                    object = alreadyThere;
                }
                else {
                    if (object != null && shouldPostProcess) {
                        try {
                            object = postProcessObjectFromFactoryBean(object, beanName);
                        }
                        catch (Throwable ex) {
                            throw new BeanCreationException(beanName,
                                    "Post-processing of FactoryBean's singleton object failed", ex);
                        }
                    }
                    //放入缓存中
                    this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
                }
            }
            return (object != NULL_OBJECT ? object : null);
        }
    }
    else {
        Object object = doGetObjectFromFactoryBean(factory, beanName);
        if (object != null && shouldPostProcess) {
            try {
                object = postProcessObjectFromFactoryBean(object, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
            }
        }
        return object;
    }
}

private Object doGetObjectFromFactoryBean(final FactoryBean factory, final String beanName)
        throws BeanCreationException {

    Object object;
    try {
        if (System.getSecurityManager() != null) {
            AccessControlContext acc = getAccessControlContext();
            try {
                object = AccessController.doPrivileged(new PrivilegedExceptionAction() {
                    @Override
                    public Object run() throws Exception {
                            return factory.getObject();
                        }
                    }, acc);
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            //这里真正的bean实例
            object = factory.getObject();
        }
    }
    catch (FactoryBeanNotInitializedException ex) {
        throw new BeanCurrentlyInCreationException(beanName, ex.toString());
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
    }

    // Do not accept a null value for a FactoryBean that's not fully
    // initialized yet: Many FactoryBeans just return null then.
    if (object == null && isSingletonCurrentlyInCreation(beanName)) {
        throw new BeanCurrentlyInCreationException(
                beanName, "FactoryBean which is currently in creation returned null from getObject");
    }
    return object;
}
 
 

6. 再来看下首次创建bean实例过程
 > AbstractBeanFactory

    ```
// 作用域是单例模式,当依赖bean创建完成,开始创建本身实例
if (mbd.isSingleton()) {
    //首先创建工厂bean
    //然后由工厂bean创建真实bean对象
    sharedInstance = getSingleton(beanName, new ObjectFactory() {
        @Override
        public Object getObject() throws BeansException {
            try {
                return createBean(beanName, mbd, args);
            }
            catch (BeansException ex) {
                // Explicitly remove instance from singleton cache: It might have been put there
                // eagerly by the creation process, to allow for circular reference resolution.
                // Also remove any beans that received a temporary reference to the bean.
                destroySingleton(beanName);
                throw ex;
            }
        }
    });
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
 
 

AbstractAutowireCapableBeanFactory

  @Override
  protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
      if (logger.isDebugEnabled()) {
          logger.debug("Creating instance of bean '" + beanName + "'");
      }
      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.
      //
      Class resolvedClass = resolveBeanClass(mbd, beanName);
      if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
          mbdToUse = new RootBeanDefinition(mbd);
          mbdToUse.setBeanClass(resolvedClass);
      }

      // Prepare method overrides.
      try {
          mbdToUse.prepareMethodOverrides();
      }
      catch (BeanDefinitionValidationException ex) {
          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.
          Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
          if (bean != null) {
              return bean;
          }
      }
      catch (Throwable ex) {
          throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                  "BeanPostProcessor before instantiation of bean failed", ex);
      }
      //这里进行真正的创建过程
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      if (logger.isDebugEnabled()) {
          logger.debug("Finished creating instance of bean '" + beanName + "'");
      }
      return beanInstance;
  }
  protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
      // Instantiate the bean.
      BeanWrapper instanceWrapper = null;
      if (mbd.isSingleton()) {
          instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
      }
      if (instanceWrapper == null) {
          //真正创建实例
          instanceWrapper = createBeanInstance(beanName, mbd, args);
      }
      final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
      Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

      // Allow post-processors to modify the merged bean definition.
      synchronized (mbd.postProcessingLock) {
          if (!mbd.postProcessed) {
              applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
              mbd.postProcessed = true;
          }
      }

      // Eagerly cache singletons to be able to resolve circular references
      // even when triggered by lifecycle interfaces like BeanFactoryAware.
      boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
              isSingletonCurrentlyInCreation(beanName));
      if (earlySingletonExposure) {
          if (logger.isDebugEnabled()) {
              logger.debug("Eagerly caching bean '" + beanName +
                      "' to allow for resolving potential circular references");
          }
          addSingletonFactory(beanName, new ObjectFactory() {
              @Override
              public Object getObject() throws BeansException {
                  return getEarlyBeanReference(beanName, mbd, bean);
              }
          });
      }

      // Initialize the bean instance.
      Object exposedObject = bean;
      try {
          //装配属性,比如属性赋值
          populateBean(beanName, mbd, instanceWrapper);
          if (exposedObject != null) {
              exposedObject = initializeBean(beanName, exposedObject, mbd);
          }
      }
      catch (Throwable ex) {
          if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
              throw (BeanCreationException) ex;
          }
          else {
              throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
          }
      }
      //存在循环依赖,提前曝光过程
      if (earlySingletonExposure) {
          Object earlySingletonReference = getSingleton(beanName, false);
          if (earlySingletonReference != null) {
              if (exposedObject == bean) {
                  exposedObject = earlySingletonReference;
              }
              else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                  String[] dependentBeans = getDependentBeans(beanName);
                  Set actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                  for (String dependentBean : dependentBeans) {
                      if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                          actualDependentBeans.add(dependentBean);
                      }
                  }
                  if (!actualDependentBeans.isEmpty()) {
                      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.
      try {
          registerDisposableBeanIfNecessary(beanName, bean, mbd);
      }
      catch (BeanDefinitionValidationException ex) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
      }

      return exposedObject;
  }
 
 
  protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
      // Make sure bean class is actually resolved at this point.
      Class beanClass = resolveBeanClass(mbd, beanName);

      if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
      }

      if (mbd.getFactoryMethodName() != null)  {
          return instantiateUsingFactoryMethod(beanName, mbd, args);
      }

      // Shortcut when re-creating the same bean...
      boolean resolved = false;
      boolean autowireNecessary = false;
      if (args == null) {
          synchronized (mbd.constructorArgumentLock) {
              if (mbd.resolvedConstructorOrFactoryMethod != null) {
                  resolved = true;
                  autowireNecessary = mbd.constructorArgumentsResolved;
              }
          }
      }
      if (resolved) {
          if (autowireNecessary) {
              return autowireConstructor(beanName, mbd, null, null);
          }
          else {
              return instantiateBean(beanName, mbd);
          }
      }

      // 反射创建带参构造器对象
      Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
      if (ctors != null ||
              mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
              mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
          return autowireConstructor(beanName, mbd, ctors, args);
      }

      // 反射创建无参数构造器对象
      return instantiateBean(beanName, mbd);
  }
   protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
       try {
           Object beanInstance;
           final BeanFactory parent = this;
           if (System.getSecurityManager() != null) {
               beanInstance = AccessController.doPrivileged(new PrivilegedAction() {
                   @Override
                   public Object run() {
                       return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                   }
               }, getAccessControlContext());
           }
           else {
               //反射创建
               beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
           }
           BeanWrapper bw = new BeanWrapperImpl(beanInstance);
           initBeanWrapper(bw);
           return bw;
       }
       catch (Throwable ex) {
           throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
       }
   }
 
 

SimpleInstantiationStrategy

   @Override
   public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
       // Don't override the class with CGLIB if no overrides.
       if (bd.getMethodOverrides().isEmpty()) {
           Constructor constructorToUse;
           synchronized (bd.constructorArgumentLock) {
               constructorToUse = (Constructor) bd.resolvedConstructorOrFactoryMethod;
               if (constructorToUse == null) {
                   final Class clazz = bd.getBeanClass();
                   if (clazz.isInterface()) {
                       throw new BeanInstantiationException(clazz, "Specified class is an interface");
                   }
                   try {
                       if (System.getSecurityManager() != null) {
                           constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction>() {
                               @Override
                               public Constructor run() throws Exception {
                                   return clazz.getDeclaredConstructor((Class[]) null);
                               }
                           });
                       }
                       else {
                           constructorToUse =  clazz.getDeclaredConstructor((Class[]) null);
                       }
                       bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                   }
                   catch (Throwable ex) {
                       throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                   }
               }
           }
           //反射创建实例
           return BeanUtils.instantiateClass(constructorToUse);
       }
       else {
           // Must generate CGLIB subclass.
           return instantiateWithMethodInjection(bd, beanName, owner);
       }
   }

BeanUtils

  public static  T instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException {
      Assert.notNull(ctor, "Constructor must not be null");
      try {
          ReflectionUtils.makeAccessible(ctor);
          //这里就完成了实例的创建
          return ctor.newInstance(args);
      }
      catch (InstantiationException ex) {
          throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
      }
      catch (IllegalAccessException ex) {
          throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
      }
      catch (IllegalArgumentException ex) {
          throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
      }
      catch (InvocationTargetException ex) {
          throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
      }
  }

7.到这里就完成了 一个简单的javaBean实例化过程

参考资料
  • Spring深度源码分析

你可能感兴趣的:(spring源码学习 - 一个简单bean的实例化过程)