(二) Bean对象实例化
上面程序中前三行对applicationContext.xml解析完成之后并没有生成bean实例,那么bean对象是在哪里实例化的?答案是在第一次获取bean实例的时候,也就是在调用DefaultListableBeanFactory的getBean的时候,注意,这里只是针对BeanFactory而言的并不是针对ApplicationContext的,ApplicationContext在实例化BeanFactory对象后会通过一个循环把所有单例bean实例化。
bean实例的创建调用轨迹如下:
1,AbstractBeanFactory.getBean(String) 2,AbstractBeanFactory.doGetBean(String, Class, Object[], boolean) 3,DefaultSingletonBeanRegistry.getSingleton(String) 4,AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[]) 5,AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[]) 6,AbstractAutowireCapableBeanFactory.createBeanInstance(String, RootBeanDefinition, Object[]) 7,AbstractAutowireCapableBeanFactory.instantiateBean(String, RootBeanDefinition) 8,SimpleInstantiationStrategy.instantiate(RootBeanDefinition, String, BeanFactory) 9, AbstractAutowireCapableBeanFactory.populateBean(String, RootBeanDefinition, BeanWrapper) 10,AbstractAutowireCapableBeanFactory.initializeBean(String, Object, RootBeanDefinition) 11,AbstractAutowireCapableBeanFactory.invokeAwareMethods(String, Object) 12,AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(Object, String) 13,AbstractAutowireCapableBeanFactory.invokeInitMethods(String, Object, RootBeanDefinition) 14,AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(Object, String)
主要类的类图:
在通过BeanFactory获取bean实例对象的时候,会先去单例集合中找是否已经创建了对应的实例,如果有就直接返回了,这里是第一次获取,所以没有拿到;然后AbastractBeanFactory会根据bean的名称获取对应的BeanDefinition对象,BeanDefinition对象代表了对应类的各种元数据,所以根据BeanDefinition对象就可以判断是否是单例,是否依赖其他对象,如果依赖了其他对象那么先生成其依赖,这里是递归调用,源码如下:
protectedT doGetBean( final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); Object bean; // 先从缓存的单例集合中获取 Object sharedInstance = getSingleton(beanName); 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 = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // 从父BeanFactory找 BeanFactory parentBeanFactory = getParentBeanFactory(); 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); } } if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // 运行到这里说明bean没有被创建,先获取此bean依赖的bean String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); //实例化依赖的bean getBean(dep); } } // 如果是单例则开始创建bean实例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory
步骤7之前都是为实例化对象做准备,真正实例化bean的是AbstractAutowireCapableBeanFactory的instantiateBean方法,其源码如下:
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); } }
其中beanInstance变量即为实例化的bean对象实例,这里用到的实例化策略类是CglibSubclassingInstantiationStrategy类,但是正使用的是其父类SimpleInstantiationStrategy的instantiate方法,此方法实例化对象就比较简单了,直接用工具类BeanUtils利用反射通过构造函数生成实例返回;源代码如下:
@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) { //这里一堆安全检查 } //默认使用构造函数利用反射实例化bean return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. return instantiateWithMethodInjection(bd, beanName, owner); } }
至此,bean实例化完成,但是对spring来说bean的实例化过程才刚刚开始,接下来一系列的处理处处体现了spring的高可扩展性,且看:
1,设置对象属性(依赖注入)
此过程是AbstractAutowireCapableBeanFactory的populateBean方法完成的,方法源码如下:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { PropertyValues pvs = mbd.getPropertyValues();//这里获取到此bean的属性以及属性值的信息 if (bw == null) { if (!pvs.isEmpty()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { return; } } boolean continueWithPropertyPopulation = true; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } //处理自动装载 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } applyPropertyValues(beanName, mbd, bw, pvs); }
此方法的最后一行调用了applyPropertyValues方法,如果此bean的属性被注册了属性编辑器,这里会调用对应的属性编辑器实现一个文本到对象的转换。至此bean的属性注入完成。
2,Aware接口的调用。
此处涉及到Aware接口的实现有如下三个:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware。此过程由AbstractAutowireCapableBeanFactory的invokeAwareMethods方法完成,其实现也很简单,源码如下:
private void invokeAwareMethods(final String beanName, final Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader()); } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } }
3,后置处理器的postProcessBeforeInitialization方法。
如果有BeanPostProcessor接口的子类被实例化到了spring容器,那么此时就会执行postProcessBeforeInitialization方法,代码如下:
@Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessBeforeInitialization(result, beanName); if (result == null) { return result; } } return result; }
4,InitializingBean接口。
如果此bean实现了InitializingBean接口,则其方法afterPropertiesSet()会被调用,源码如下:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isDebugEnabled()) { logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override public Object run() throws Exception { ((InitializingBean) bean).afterPropertiesSet(); return null; } }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { //调用afterPropertiesSet方法 ((InitializingBean) bean).afterPropertiesSet(); } } if (mbd != null) { String initMethodName = mbd.getInitMethodName(); if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); } } }
5,执行init-method方法。
如果指定了init-method方法,则此方法被执行,源码如下:
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { //省略一堆校验 if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override public Object run() throws Exception { ReflectionUtils.makeAccessible(initMethod); return null; } }); try { AccessController.doPrivileged(new PrivilegedExceptionAction () { @Override public Object run() throws Exception { initMethod.invoke(bean); return null; } }, getAccessControlContext()); } catch (PrivilegedActionException pae) { InvocationTargetException ex = (InvocationTargetException) pae.getException(); throw ex.getTargetException(); } } else { try { ReflectionUtils.makeAccessible(initMethod); //通过反射执行指定init-Mothod initMethod.invoke(bean); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }
6,后置处理器的postProcessAfterInitialization方法。
如果有BeanPostProcessor接口子类被实例化到了spring容器,那么此时就会执行postProcessAfterInitialization方法,源码如下:
@Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) { result = beanProcessor.postProcessAfterInitialization(result, beanName); if (result == null) { return result; } } return result; }
以上2,3,4,5,6步骤发生在AbstractAutowireCapableBeanFactory的initializeBean方法内,源码如下:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { invokeAwareMethods(beanName, bean); return null; } }, getAccessControlContext()); } else { //②Aware接口 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { //③postProcessBeforeInitialization方法 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { //④ InitializingBean接口、⑤init-Method invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { //⑥ postProcessAfterInitialization方法 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
至此,bean实例化完成,当调用AbstractApplicationContext的close()时,如果bean指定了destroy-method方法,则指定的方法被执行,bean被销毁,至此bean的生命周期结束。