接着上一小节的内容继续,从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这里进入会从缓存中拿去之前已经收集好的InjectionMetadataInjectionMetadata metadata = https://tazarkount.com/read/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或者methodCollection 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 = https://tazarkount.com/read/AutowiredAnnotationBeanPostProcessor.this.resolvedCachedArgument(beanName, this.cachedFieldValue);} else {DependencyDescriptor desc = new DependencyDescriptor(field, this.required);desc.setContainingClass(bean.getClass());Set 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 DefaultListableBeanFactory 907 N347public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set DefaultListableBeanFactory 928 N348public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set 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@PostConstructwrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);}try {//N357InitializingBean接口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类型则调用这个接口的实现方法setBeanNameif (bean instanceof BeanNameAware) {((BeanNameAware)bean).setBeanName(beanName);}//然后判断如果是调用BeanClassLoaderAware类型则调用这个接口的实现方法setBeanClassLoaderif (bean instanceof BeanClassLoaderAware) {ClassLoader bcl = this.getBeanClassLoader();if (bcl != null) {((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);}}//然后判断如果是调用BeanFactoryAware类型则调用这个接口的实现方法setBeanFactoryif (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();//N353ApplicationContextAwareProcessor//N355InitDestroyAnnotationBeanPostProcessorcurrent = 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 = https://tazarkount.com/read/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 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这个LinkedHashMapthis.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 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) {//N364this.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() {//N366this.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());}//循环遍历上面生成的数组,数组元素是所有keyfor(int i = disposableBeanNames.length - 1; i >= 0; --i) {//N367this.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这个容器中,删除的同时会获取到这个adapterdisposableBean = (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 DisposableBeanAdapter 143 N369public void destroy() {//首先这里会拿到之前构造函数中处理好了并存到容器中的bp//然后调用postProcessBeforeDestruction方法来调用带有@preDestroyif (!CollectionUtils.isEmpty(this.beanPostProcessors)) {Iterator var1 = this.beanPostProcessors.iterator();while(var1.hasNext()) {DestructionAwareBeanPostProcessor processor = (DestructionAwareBeanPostProcessor)var1.next();//N370initDestroyAnnotationBeanPostProcessor这个方法会调用到之前收集好的带有@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 = https://tazarkount.com/read/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 【六 Spring源码解析-Bean的实例化流程(下)】至此,整个实例化的大体流程已经完全结束了,Spring专题接下来一小节会是讲解循环依赖的相关源码和场景分析 。Spring已经讲了六小节了,有疑问的读者可以在评论区提出来大家讨论一下,笔者一定知无不言 。
- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
