> 文档中心 > Spring源码解析(六)-Bean的实例化流程(下)

Spring源码解析(六)-Bean的实例化流程(下)

接着上一小节的内容继续,从N313的this.populateBean(beanName, mbd, instanceWrapper)方法调用继续讲解。

AbstractAutowireCapableBeanFactory 863 N342protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { if (bw == null) {     if (mbd.hasPropertyValues()) {  throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");     } } else {     boolean continueWithPropertyPopulation = true;     if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {  Iterator var5 = this.getBeanPostProcessors().iterator();  while(var5.hasNext()) {      BeanPostProcessor bp = (BeanPostProcessor)var5.next();      if (bp instanceof InstantiationAwareBeanPostProcessor) {   InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;   if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {continueWithPropertyPopulation = false;break;   }      }  }     }     if (continueWithPropertyPopulation) {  PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;  if (mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2) {      MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);      if (mbd.getResolvedAutowireMode() == 1) {   this.autowireByName(beanName, mbd, bw, newPvs);      }      if (mbd.getResolvedAutowireMode() == 2) {   this.autowireByType(beanName, mbd, bw, newPvs);      }      pvs = newPvs;  }  boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();  boolean needsDepCheck = mbd.getDependencyCheck() != 0;  PropertyDescriptor[] filteredPds = null;  if (hasInstAwareBpps) {      if (pvs == null) {   pvs = mbd.getPropertyValues();      }      Iterator var9 = this.getBeanPostProcessors().iterator();      while(var9.hasNext()) {   BeanPostProcessor bp = (BeanPostProcessor)var9.next();   if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;//N343   依赖注入过程,@Autowired的支持PropertyValues pvsToUse = ibp.postProcessProperties((PropertyValues)pvs, bw.getWrappedInstance(), beanName);if (pvsToUse == null) {    if (filteredPds == null) { filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);    }    pvsToUse = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);    if (pvsToUse == null) { return;    }}pvs = pvsToUse;   }      }  }  if (needsDepCheck) {      if (filteredPds == null) {   filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);      }      this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);  }  if (pvs != null) {      //这个地方就是xml的起作用的地方      this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);  }     } }    }
AutowiredAnnotationBeanPostProcessor 247 N343public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {    //N336  这里进入会从缓存中拿去之前已经收集好的InjectionMetadata InjectionMetadata metadata = this.findAutowiringMetadata(beanName, bean.getClass(), pvs); try {     //344  拿到metadate后开始遍历并且执行相应逻辑     metadata.inject(bean, beanName, pvs);     return pvs; } catch (BeanCreationException var6) {     throw var6; } catch (Throwable var7) {     throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", var7); }    }
InjectionMetadata 56 N344public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {    //在InjectionMetadata中已经存好了InjectedElement集合,这些集合存的带有@autowired的field或者method Collection<InjectionMetadata.InjectedElement> checkedElements = this.checkedElements; Collection<InjectionMetadata.InjectedElement> elementsToIterate = checkedElements != null ? checkedElements : this.injectedElements; InjectionMetadata.InjectedElement element; if (!((Collection)elementsToIterate).isEmpty()) {     //遍历收集到的集合中的一个个InjectedElement     //N345和N346  这里有两个实现类     for(Iterator var6 = ((Collection)elementsToIterate).iterator(); var6.hasNext(); element.inject(target, beanName, pvs)) {  element = (InjectionMetadata.InjectedElement)var6.next();  if (logger.isTraceEnabled()) {      logger.trace("Processing injected element of bean '" + beanName + "': " + element);  }     } }    }
AutowiredAnnotationBeanPostProcessor 536 N345protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {     Field field = (Field)this.member;     Object value;     if (this.cached) {  value = AutowiredAnnotationBeanPostProcessor.this.resolvedCachedArgument(beanName, this.cachedFieldValue);     } else {  DependencyDescriptor desc = new DependencyDescriptor(field, this.required);  desc.setContainingClass(bean.getClass());  Set<String> autowiredBeanNames = new LinkedHashSet(1);  Assert.state(AutowiredAnnotationBeanPostProcessor.this.beanFactory != null, "No BeanFactory available");  TypeConverter typeConverter = AutowiredAnnotationBeanPostProcessor.this.beanFactory.getTypeConverter();  try {      //N347   这里拿到需要注入的值,而spring获取引用类型的值只有一种方法,调用Factory.getBean()      value = AutowiredAnnotationBeanPostProcessor.this.beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);  } catch (BeansException var12) {      throw new UnsatisfiedDependencyException((String)null, beanName, new InjectionPoint(field), var12);  }  synchronized(this) {      if (!this.cached) {   if (value == null && !this.required) {this.cachedFieldValue = null;   } else {this.cachedFieldValue = desc;AutowiredAnnotationBeanPostProcessor.this.registerDependentBeans(beanName, autowiredBeanNames);if (autowiredBeanNames.size() == 1) {    String autowiredBeanName = (String)autowiredBeanNames.iterator().next();    if (AutowiredAnnotationBeanPostProcessor.this.beanFactory.containsBean(autowiredBeanName) && AutowiredAnnotationBeanPostProcessor.this.beanFactory.isTypeMatch(autowiredBeanName, field.getType())) { this.cachedFieldValue = new AutowiredAnnotationBeanPostProcessor.ShortcutDependencyDescriptor(desc, autowiredBeanName, field.getType());    }}   }   this.cached = true;      }  }     }     if (value != null) {  //前面一大段获取到了需要注入的属性值,这里就反射注入值  ReflectionUtils.makeAccessible(field);  field.set(bean, value);     } }
AutowiredAnnotationBeanPostProcessor 436 N346protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {     if (!this.checkPropertySkipping(pvs)) {  Method method = (Method)this.member;  Object[] arguments;  if (this.cached) {      arguments = this.resolveCachedArguments(beanName);  } else {      Class<?>[] paramTypes = method.getParameterTypes();      arguments = new Object[paramTypes.length];      DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];      Set<String> autowiredBeans = new LinkedHashSet(paramTypes.length);      Assert.state(AutowiredAnnotationBeanPostProcessor.this.beanFactory != null, "No BeanFactory available");      TypeConverter typeConverter = AutowiredAnnotationBeanPostProcessor.this.beanFactory.getTypeConverter();      for(int i = 0; i < arguments.length; ++i) {   MethodParameter methodParam = new MethodParameter(method, i);   DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);   currDesc.setContainingClass(bean.getClass());   descriptors[i] = currDesc;   try {//347  spring获取引用类型的值只有一种方法,调用Factory.getBean()。这个方法到最后会调用Factory.getBean()拿到实例 Object arg = AutowiredAnnotationBeanPostProcessor.this.beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);if (arg == null && !this.required) {    arguments = null;    break;}arguments[i] = arg;   } catch (BeansException var18) {throw new UnsatisfiedDependencyException((String)null, beanName, new InjectionPoint(methodParam), var18);   }      }      synchronized(this) {   if (!this.cached) {if (arguments != null) {    Object[] cachedMethodArguments = new Object[paramTypes.length];    System.arraycopy(descriptors, 0, cachedMethodArguments, 0, arguments.length);    AutowiredAnnotationBeanPostProcessor.this.registerDependentBeans(beanName, autowiredBeans);    if (autowiredBeans.size() == paramTypes.length) { Iterator<String> it = autowiredBeans.iterator(); for(int ix = 0; ix < paramTypes.length; ++ix) {     String autowiredBeanName = (String)it.next();     if (AutowiredAnnotationBeanPostProcessor.this.beanFactory.containsBean(autowiredBeanName) && AutowiredAnnotationBeanPostProcessor.this.beanFactory.isTypeMatch(autowiredBeanName, paramTypes[ix])) {  cachedMethodArguments[ix] = new AutowiredAnnotationBeanPostProcessor.ShortcutDependencyDescriptor(descriptors[ix], autowiredBeanName, paramTypes[ix]);     } }    }    this.cachedMethodArguments = cachedMethodArguments;} else {    this.cachedMethodArguments = null;}this.cached = true;   }      }  }  if (arguments != null) {      try {   //通过上面一大堆代码拿到了方法的参数实例,通过反射调用执行此方法   ReflectionUtils.makeAccessible(method);   method.invoke(bean, arguments);      } catch (InvocationTargetException var16) {   throw var16.getTargetException();      }  }     } }
DefaultListableBeanFactory 907 N347public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(this.getParameterNameDiscoverer()); if (Optional.class == descriptor.getDependencyType()) {     return this.createOptionalDependency(descriptor, requestingBeanName); } else if (ObjectFactory.class != descriptor.getDependencyType() && ObjectProvider.class != descriptor.getDependencyType()) {     if (javaxInjectProviderClass == descriptor.getDependencyType()) {  return (new DefaultListableBeanFactory.Jsr330Factory()).createDependencyProvider(descriptor, requestingBeanName);     } else {  Object result = this.getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName);  if (result == null) {      //N348  继续往里找肯定有getBean方法      result = this.doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);  }  return result;     } } else {     return new DefaultListableBeanFactory.DependencyObjectProvider(descriptor, requestingBeanName); }    }
DefaultListableBeanFactory 928 N348public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor); Object var14; try {     Object shortcut = descriptor.resolveShortcut(this);     if (shortcut != null) {  Object var18 = shortcut;  return var18;     }     Class<?> type = descriptor.getDependencyType();     Object value = this.getAutowireCandidateResolver().getSuggestedValue(descriptor);     Object var21;     if (value != null) {  if (value instanceof String) {      String strVal = this.resolveEmbeddedValue((String)value);      BeanDefinition bd = beanName != null && this.containsBean(beanName) ? this.getMergedBeanDefinition(beanName) : null;      value = this.evaluateBeanDefinitionString(strVal, bd);  }  TypeConverter converter = typeConverter != null ? typeConverter : this.getTypeConverter();  var21 = descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter());  return var21;     }     Object multipleBeans = this.resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);     if (multipleBeans != null) {  var21 = multipleBeans;  return var21;     }     Map<String, Object> matchingBeans = this.findAutowireCandidates(beanName, type, descriptor);     String autowiredBeanName;     if (matchingBeans.isEmpty()) {  if (this.isRequired(descriptor)) {      this.raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);  }  autowiredBeanName = null;  return autowiredBeanName;     }     Object instanceCandidate;     Object result;     if (matchingBeans.size() > 1) {  autowiredBeanName = this.determineAutowireCandidate(matchingBeans, descriptor);  if (autowiredBeanName == null) {      if (this.isRequired(descriptor) || !this.indicatesMultipleBeans(type)) {   result = descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);   return result;      }      result = null;      return result;  }  instanceCandidate = matchingBeans.get(autowiredBeanName);     } else {  Entry<String, Object> entry = (Entry)matchingBeans.entrySet().iterator().next();  autowiredBeanName = (String)entry.getKey();  instanceCandidate = entry.getValue();     }     if (autowiredBeanNames != null) {  autowiredBeanNames.add(autowiredBeanName);     }     if (instanceCandidate instanceof Class) {  //N349  在这里真正拿到了构造函数中依赖的实例  instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);     }     result = instanceCandidate;     if (instanceCandidate instanceof NullBean) {  if (this.isRequired(descriptor)) {      this.raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);  }  result = null;     }     if (!ClassUtils.isAssignableValue(type, result)) {  throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());     }     var14 = result; } finally {     ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } return var14;    }
DependencyDescriptor 139 N349public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) throws BeansException {    //终于找到了beanFactory.getBean(beanName),就是这里拿到了需要注入的实例 return beanFactory.getBean(beanName);    }
AbstractAutowireCapableBeanFactory 1162 N350protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() != null) {     AccessController.doPrivileged(() -> {  this.invokeAwareMethods(beanName, bean);  return null;     }, this.getAccessControlContext()); } else {     //N351   调用Aware方法     this.invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) {     //N352   @PostConstruct     wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); } try {     //N357    InitializingBean接口     this.invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable var6) {     throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6); } if (mbd == null || !mbd.isSynthetic()) {     //这里请大家记住,因为这个方法调用beanPostProcess是AOP的入口,后面会从这里开始讲解AOP     //还有另一个入口是在循环依赖的时候,也会专门讲到     wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean;    }
AbstractAutowireCapableBeanFactory 1190 N351private void invokeAwareMethods(String beanName, Object bean) {    //首先判断是不是Aware类型 if (bean instanceof Aware) {     //然后判断如果是调用BeanNameAware类型则调用这个接口的实现方法setBeanName     if (bean instanceof BeanNameAware) {  ((BeanNameAware)bean).setBeanName(beanName);     }//然后判断如果是调用BeanClassLoaderAware类型则调用这个接口的实现方法setBeanClassLoader     if (bean instanceof BeanClassLoaderAware) {  ClassLoader bcl = this.getBeanClassLoader();  if (bcl != null) {      ((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);  }     }//然后判断如果是调用BeanFactoryAware类型则调用这个接口的实现方法setBeanFactory     if (bean instanceof BeanFactoryAware) {  ((BeanFactoryAware)bean).setBeanFactory(this);     } }    }
AbstractAutowireCapableBeanFactory 246 N352public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; Object current; for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {     BeanPostProcessor processor = (BeanPostProcessor)var4.next();     //N353  ApplicationContextAwareProcessor     //N355  InitDestroyAnnotationBeanPostProcessor     current = processor.postProcessBeforeInitialization(result, beanName);     if (current == null) {  return result;     } } return result;    }
ApplicationContextAwareProcessor 34 N353public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { AccessControlContext acc = null; if (System.getSecurityManager() != null && (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware || bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {     acc = this.applicationContext.getBeanFactory().getAccessControlContext(); } if (acc != null) {     AccessController.doPrivileged(() -> {  this.invokeAwareInterfaces(bean);  return null;     }, acc); } else {     //354   在这里执行主要的业务逻辑,也是对多种不同的Aware的调用     this.invokeAwareInterfaces(bean); } return bean;    }
ApplicationContextAwareProcessor 52 N354private void invokeAwareInterfaces(Object bean) { if (bean instanceof Aware) {     if (bean instanceof EnvironmentAware) {  ((EnvironmentAware)bean).setEnvironment(this.applicationContext.getEnvironment());     }     if (bean instanceof EmbeddedValueResolverAware) {  ((EmbeddedValueResolverAware)bean).setEmbeddedValueResolver(this.embeddedValueResolver);     }     if (bean instanceof ResourceLoaderAware) {  ((ResourceLoaderAware)bean).setResourceLoader(this.applicationContext);     }     if (bean instanceof ApplicationEventPublisherAware) {  ((ApplicationEventPublisherAware)bean).setApplicationEventPublisher(this.applicationContext);     }     if (bean instanceof MessageSourceAware) {  ((MessageSourceAware)bean).setMessageSource(this.applicationContext);     }     if (bean instanceof ApplicationContextAware) {  //这个类型是获取到ApplicationContext对象实例  ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);     } }    }
InitDestroyAnnotationBeanPostProcessor 69 N355public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {    //N332   之前运行过一遍是为了收集带有@postConstruct注解的方法,现在就可以直接获取到了 InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata metadata = this.findLifecycleMetadata(bean.getClass()); try {     //N356  调用@PostConstruct注解的方法     metadata.invokeInitMethods(bean, beanName);     return bean; } catch (InvocationTargetException var5) {     throw new BeanCreationException(beanName, "Invocation of init method failed", var5.getTargetException()); } catch (Throwable var6) {     throw new BeanCreationException(beanName, "Failed to invoke init method", var6); }    }
InitDestroyAnnotationBeanPostProcessor 259 N356   //类似N144接口,@autowired的属性或方法注入public void invokeInitMethods(Object target, String beanName) throws Throwable {     Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> checkedInitMethods = this.checkedInitMethods;     Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> initMethodsToIterate = checkedInitMethods != null ? checkedInitMethods : this.initMethods;     InitDestroyAnnotationBeanPostProcessor.LifecycleElement element;     if (!((Collection)initMethodsToIterate).isEmpty()) {  //遍历集合,反射调用。带@postConstruct注解的方法是没有参数的,所以下面是没有参数的方法反射  for(Iterator var5 = ((Collection)initMethodsToIterate).iterator(); var5.hasNext(); element.invoke(target)) {      element = (InitDestroyAnnotationBeanPostProcessor.LifecycleElement)var5.next();      if (InitDestroyAnnotationBeanPostProcessor.this.logger.isTraceEnabled()) {   InitDestroyAnnotationBeanPostProcessor.this.logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod());      }  }     } }
AbstractAutowireCapableBeanFactory 1210 N357protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = bean instanceof InitializingBean;    //这里是对InitializingBean接口的处理,如果bean继承了该接口,则进入if,调用afterPropertiesSet方法 if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {     if (this.logger.isTraceEnabled()) {  this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");     }     if (System.getSecurityManager() != null) {  try {      AccessController.doPrivileged(() -> {   ((InitializingBean)bean).afterPropertiesSet();   return null;      }, this.getAccessControlContext());  } catch (PrivilegedActionException var6) {      throw var6.getException();  }     } else {  //这里是对接口实现方法afterPropertiesSet()调用  ((InitializingBean)bean).afterPropertiesSet();     } }//这里是对init-method属性的调用(这个就是xml中的init-method属性) if (mbd != null && bean.getClass() != NullBean.class) {     String initMethodName = mbd.getInitMethodName();     if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {  this.invokeCustomInitMethod(beanName, bean, mbd);     } }    }
AbstractBeanFactory 1156 N358protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) { AccessControlContext acc = System.getSecurityManager() != null ? this.getAccessControlContext() : null;    //对于多例的实例是没有存入缓存的 if (!mbd.isPrototype() && this.requiresDestruction(bean, mbd)) {     //这里是处理单例的     if (mbd.isSingleton()) {  //N359  他会将beanName和DisposableBeanAdapter映射到disposableBeans这个LinkedHashMap  this.registerDisposableBean(beanName,//N360   现在进入这个对象看看      new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessors(), acc));     } else {  //这里是处理非单例的(思路跟上面差不多的,可以自己探索试试)  Scope scope = (Scope)this.scopes.get(mbd.getScope());  if (scope == null) {      throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");  }  scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessors(), acc));     } }    }
DefaultSingletonBeanRegistry 232 N359public void registerDisposableBean(String beanName, DisposableBean bean) {     //这个map就是专门存销毁对象的对象,容器销毁之前会循环遍历这个map并调用每个销毁对象的对象 synchronized(this.disposableBeans) {     this.disposableBeans.put(beanName, bean); }    }
N360   //这个是DisposableBeanAdapter的构造函数public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition, List<BeanPostProcessor> postProcessors, @Nullable AccessControlContext acc) { Assert.notNull(bean, "Disposable bean must not be null"); this.bean = bean; this.beanName = beanName;    //这里是判断当前bean是否为DisposableBean的实现类,如果是则设为true this.invokeDisposableBean = this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy"); this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed(); this.acc = acc;    //这里首先获取到DestroyMethod的方法名字(也就是在xml中的destroy-method属性的值,从beanDefinition中获取) String destroyMethodName = this.inferDestroyMethodIfNecessary(bean, beanDefinition); if (destroyMethodName != null && (!this.invokeDisposableBean || !"destroy".equals(destroyMethodName)) && !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {     //如果bd中有这个属性的值则会进入这里面,将上面局部变量值赋给Adapter的成员变量destroyMethodName     this.destroyMethodName = destroyMethodName;     //这里是获取到这个destroyMethodName的方法封装成Method类型的对象     this.destroyMethod = this.determineDestroyMethod(destroyMethodName);     if (this.destroyMethod == null) {  if (beanDefinition.isEnforceDestroyMethod()) {      throw new BeanDefinitionValidationException("Could not find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'");  }     } else {  Class<?>[] paramTypes = this.destroyMethod.getParameterTypes();  if (paramTypes.length > 1) {      throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + beanName + "' has more than one parameter - not supported as destroy method");  }  if (paramTypes.length == 1 && Boolean.TYPE != paramTypes[0]) {      throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" + beanName + "' has a non-boolean parameter - not supported as destroy method");  }     } }//这里会循环所有bpp将收集了@PreDestroy的bpp放入到this.beanPostProcessors(应该是只有InitDestroyAnnotationBeanPostProcessor) this.beanPostProcessors = this.filterPostProcessors(postProcessors, bean);    }
N161***//上面N358-N360之间是对销毁操作的一个规范,而这些操作的规范总该有个地方去调用它,也就是在什么情况下由哪里调用这些操作呢?答案就是有tomcat根据servlet规范在容器销毁前会调用N362的方法    //N361--371    容器销毁前bean的销毁过程
N361public void contextDestroyed(ServletContextEvent event) {    //N362closeWebApplicationContext(event.getServletContext());ContextCleanupListener.cleanupAttributes(event.getServletContext());}
ContextLoader 245 N362public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); boolean var6 = false; try {     var6 = true;     if (this.context instanceof ConfigurableWebApplicationContext) {  //363  ((ConfigurableWebApplicationContext)this.context).close();  var6 = false;     } else {  var6 = false;     } } finally {     if (var6) {  ClassLoader ccl = Thread.currentThread().getContextClassLoader();  if (ccl == ContextLoader.class.getClassLoader()) {      currentContext = null;  } else if (ccl != null) {      currentContextPerThread.remove(ccl);  }  servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);     } } ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) {     currentContext = null; } else if (ccl != null) {     currentContextPerThread.remove(ccl); } servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);    }
AbstractApplicationContext 524 N363public void close() { synchronized(this.startupShutdownMonitor) {     //N364     this.doClose();     if (this.shutdownHook != null) {  try {      Runtime.getRuntime().removeShutdownHook(this.shutdownHook);  } catch (IllegalStateException var4) {  }     } }    }
AbstractApplicationContext 537 N364protected void doClose() { if (this.active.get() && this.closed.compareAndSet(false, true)) {     if (this.logger.isDebugEnabled()) {  this.logger.debug("Closing " + this);     }     LiveBeansView.unregisterApplicationContext(this);     try {  this.publishEvent((ApplicationEvent)(new ContextClosedEvent(this)));     } catch (Throwable var3) {  this.logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", var3);     }     if (this.lifecycleProcessor != null) {  try {      this.lifecycleProcessor.onClose();  } catch (Throwable var2) {      this.logger.warn("Exception thrown from LifecycleProcessor on context close", var2);  }     }//365  这里是处理销毁的逻辑     this.destroyBeans();     this.closeBeanFactory();     this.onClose();     this.active.set(false); }    }
AbstractApplicationContext 567 N365protected void destroyBeans() {    //N366 this.getBeanFactory().destroySingletons();    }
DefaultSingletonBeanRegistry 335 N366public void destroySingletons() { if (this.logger.isTraceEnabled()) {     this.logger.trace("Destroying singletons in " + this); } synchronized(this.singletonObjects) {     this.singletonsCurrentlyInDestruction = true; } String[] disposableBeanNames; synchronized(this.disposableBeans) {     //这个this.disposableBeans应该很熟悉了,之前每个beanName都映射了一个Adapter到这个容器中。也就是存储了之前收集     //到该bean销毁方法的adapter对象(N160).     disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet()); }//循环遍历上面生成的数组,数组元素是所有key for(int i = disposableBeanNames.length - 1; i >= 0; --i) {     //N367       this.destroySingleton(disposableBeanNames[i]); } this.containedBeanMap.clear(); this.dependentBeanMap.clear(); this.dependenciesForBeanMap.clear(); this.clearSingletonCache();    }
DefaultSingletonBeanRegistry 369 N367public void destroySingleton(String beanName) { this.removeSingleton(beanName); DisposableBean disposableBean; synchronized(this.disposableBeans) {     //这里会删除这个bean的销毁adapter在disposableBeans这个容器中,删除的同时会获取到这个adapter     disposableBean = (DisposableBean)this.disposableBeans.remove(beanName); }//N368  然后调用一次这个adapter的destroy方法 this.destroyBean(beanName, disposableBean);    }
DefaultSingletonBeanRegistry 379 N368protected void destroyBean(String beanName, @Nullable DisposableBean bean) { Set dependencies; synchronized(this.dependentBeanMap) {     dependencies = (Set)this.dependentBeanMap.remove(beanName); } if (dependencies != null) {     if (this.logger.isTraceEnabled()) {  this.logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);     }     Iterator var4 = dependencies.iterator();     while(var4.hasNext()) {  String dependentBeanName = (String)var4.next();  this.destroySingleton(dependentBeanName);     } } if (bean != null) {     try {  //N369   这里就调到了最重要的方法,adapter的对象的destroy方法,这个方法是调用之前构造函数收集到的方法来执行销毁操作  bean.destroy();     } catch (Throwable var13) {  if (this.logger.isInfoEnabled()) {      this.logger.info("Destroy method on bean with name '" + beanName + "' threw an exception", var13);  }     } } Set containedBeans; synchronized(this.containedBeanMap) {     containedBeans = (Set)this.containedBeanMap.remove(beanName); } if (containedBeans != null) {     Iterator var15 = containedBeans.iterator();     while(var15.hasNext()) {  String containedBeanName = (String)var15.next();  this.destroySingleton(containedBeanName);     } } synchronized(this.dependentBeanMap) {     Iterator it = this.dependentBeanMap.entrySet().iterator();     while(it.hasNext()) {  Entry<String, Set<String>> entry = (Entry)it.next();  Set<String> dependenciesToClean = (Set)entry.getValue();  dependenciesToClean.remove(beanName);  if (dependenciesToClean.isEmpty()) {      it.remove();  }     } } this.dependenciesForBeanMap.remove(beanName);    }
DisposableBeanAdapter 143 N369public void destroy() {    //首先这里会拿到之前构造函数中处理好了并存到容器中的bp    //然后调用postProcessBeforeDestruction方法来调用带有@preDestroy if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {     Iterator var1 = this.beanPostProcessors.iterator();     while(var1.hasNext()) {  DestructionAwareBeanPostProcessor processor = (DestructionAwareBeanPostProcessor)var1.next();  //N370  initDestroyAnnotationBeanPostProcessor这个方法会调用到之前收集好的带有@preDestroy的方法  processor.postProcessBeforeDestruction(this.bean, this.beanName);     } }//这里是判断当前销毁的bean是否实现DisposableBean的接口,在构造函数中已经判断好并用true或false来表示 if (this.invokeDisposableBean) {     if (logger.isTraceEnabled()) {  logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");     }     try {  if (System.getSecurityManager() != null) {      AccessController.doPrivileged(() -> {   //如果是实现DisposableBean的接口则会调用实现类中的destroy   ((DisposableBean)this.bean).destroy();   return null;      }, this.acc);  } else {      ((DisposableBean)this.bean).destroy();  }     } catch (Throwable var3) {  String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";  if (logger.isDebugEnabled()) {      logger.info(msg, var3);  } else {      logger.info(msg + ": " + var3);  }     } } if (this.destroyMethod != null) {     //这里是判断是否存在destory-method属性(xml中),如果存在在构造函数中已经对这个属性收集好了并封装成Method对象     //然后该方法会先获取参数在通过反射调用,就不细看了,应该都能想明白     this.invokeCustomDestroyMethod(this.destroyMethod); } else if (this.destroyMethodName != null) {     Method methodToCall = this.determineDestroyMethod(this.destroyMethodName);     if (methodToCall != null) {  this.invokeCustomDestroyMethod(methodToCall);     } }    }
InitDestroyAnnotationBeanPostProcessor 86 N370public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {    //N332  之前运行过一遍是为了收集带有@preDestroy注解的方法,现在就可以直接获取到了 InitDestroyAnnotationBeanPostProcessor.LifecycleMetadata metadata = this.findLifecycleMetadata(bean.getClass()); try {     //N371  调用这些带有@preDestroy的方法     metadata.invokeDestroyMethods(bean, beanName); } catch (InvocationTargetException var6) {     String msg = "Destroy method on bean with name '" + beanName + "' threw an exception";     if (this.logger.isDebugEnabled()) {  this.logger.warn(msg, var6.getTargetException());     } else {  this.logger.warn(msg + ": " + var6.getTargetException());     } } catch (Throwable var7) {     this.logger.warn("Failed to invoke destroy method on bean with name '" + beanName + "'", var7); }    }
InitDestroyAnnotationBeanPostProcessor 274 N371public void invokeDestroyMethods(Object target, String beanName) throws Throwable {     Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> checkedDestroyMethods = this.checkedDestroyMethods;     Collection<InitDestroyAnnotationBeanPostProcessor.LifecycleElement> destroyMethodsToUse = checkedDestroyMethods != null ? checkedDestroyMethods : this.destroyMethods;     InitDestroyAnnotationBeanPostProcessor.LifecycleElement element;     if (!((Collection)destroyMethodsToUse).isEmpty()) {  //如果集合不为空,也就是存在带有@preDestroy的方法,循环遍历通过反射调用这些方法  for(Iterator var5 = ((Collection)destroyMethodsToUse).iterator(); var5.hasNext(); element.invoke(target)) {      element = (InitDestroyAnnotationBeanPostProcessor.LifecycleElement)var5.next();      if (InitDestroyAnnotationBeanPostProcessor.this.logger.isTraceEnabled()) {   InitDestroyAnnotationBeanPostProcessor.this.logger.trace("Invoking destroy method on bean '" + beanName + "': " + element.getMethod());      }  }     } }

至此,整个实例化的大体流程已经完全结束了,Spring专题接下来一小节会是讲解循环依赖的相关源码和场景分析。Spring已经讲了六小节了,有疑问的读者可以在评论区提出来大家讨论一下,笔者一定知无不言。

唱吧