美文网首页springspring
spring源码分析3

spring源码分析3

作者: 念䋛 | 来源:发表于2021-08-20 21:16 被阅读0次

    populateBean(beanName, mbd, instanceWrapper);方法

    exposedObject = initializeBean(beanName, exposedObject, mbd);

    populateBean是执行后置处理器,其主要的作用就是为标注了@Autowired @Value @Resources属性赋值,和xml属性赋值,xml有byName和byType之分

    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    //如果bw证明对象还没有被实例化
       if (bw == null) {
    //没有实例化,但是还有要赋值的属性,抛出异常
          if (mbd.hasPropertyValues()) {
             throw new BeanCreationException(
                   mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
          }
          else {
             // Skip property population phase for null instance.
             return;
          }
       }
    
    
    //调用InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation,方法返回//boolean类型,因为会遍历所有InstantiationAwareBeanPostProcessor实现类的//postProcessAfterInstantiation 方法,如果自己的类postProcessAfterInstantiation 方//法返回false的话,下面方法return,直接跳出方法,下面有执行postProcessProperties的//代码就不会执行,也就不会为@Autowired @Resource @Value 赋值了spring自带的都返回//true,我也没想好什么情况下需要返回false
       if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
    // InstantiationAwareBeanPostProcessor调用postProcessAfterInstantiation方法
          for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
             if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                return;
             }
          }
       }
    
       PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    //下面是xml的方式赋值,这里跳过
       int resolvedAutowireMode = mbd.getResolvedAutowireMode();
       if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
          MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
          // Add property values based on autowire by name if applicable.
          if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
             autowireByName(beanName, mbd, bw, newPvs);
          }
          // Add property values based on autowire by type if applicable.
          if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
             autowireByType(beanName, mbd, bw, newPvs);
          }
          pvs = newPvs;
       }
    
       boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
       boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
    
       PropertyDescriptor[] filteredPds = null;
       if (hasInstAwareBpps) {
          if (pvs == null) {
             pvs = mbd.getPropertyValues();
          }
    //调用InstantiationAwareBeanPostProcessor的postProcessProperties方法
    //两个重要AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor
    //类的postProcessProperties方法,分别为@Autowired @Value和@Resource属性赋值
          for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
             PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
             if (pvsToUse == null) {
                if (filteredPds == null) {
                   filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                }
                pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {
                   return;
                }
             }
             pvs = pvsToUse;
          }
       }
       if (needsDepCheck) {
          if (filteredPds == null) {
             filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
          }
          checkDependencies(beanName, mbd, filteredPds, pvs);
       }
    
       if (pvs != null) {
          applyPropertyValues(beanName, mbd, bw, pvs);
       }
    }
    
    

    exposedObject = initializeBean(beanName, exposedObject, mbd);调用绝大多数的aware

    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
       if (System.getSecurityManager() != null) {
          AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
             invokeAwareMethods(beanName, bean);
             return null;
          }, getAccessControlContext());
       }
       else {
    //调用BeanNameAware BeanClassLoaderAware BeanFactoryAware
          invokeAwareMethods(beanName, bean);
       }
    
       Object wrappedBean = bean;
       if (mbd == null || !mbd.isSynthetic()) {
    // 1.ApplicationContextAwareProcessor调用EnvironmentAware, //EmbeddedValueResolverAware
    //ResourceLoaderAware
    //ApplicationEventPublisherAware
    //MessageSourceAware
    //ApplicationStartupAware
    //ApplicationContextAware
    //2.ConfigurationClassPostProcessor的静态内部类
    //ImportAwareBeanPostProcessor的调用ImportAware
    //3. CommonAnnotationBeanPostProcessor extends //InitDestroyAnnotationBeanPostProcessor 调用@PostConstruct
          wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
       }
    
       try {
    //判断bean是否实现了InitializingBean接口,判断是否有@Bean的方式注入Bean时,是否定义了@Bean(initMethod = "world") initMethod方法
          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()) {
    //调用Bean后置处理器(最后一个),此时的bean已经初始化完成了,看名称也能看出来Initialization初始化的意思,这里更多的十根据我们的需要,自己实现
          wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
       }
    
       return wrappedBean;
    }
    
    invokeInitMethods方法
    
    protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
          throws Throwable {
    //是否实现了InitializingBean接口
       boolean isInitializingBean = (bean instanceof InitializingBean);
       if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
          if (logger.isTraceEnabled()) {
             logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
          }
          if (System.getSecurityManager() != null) {
             try {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                   ((InitializingBean) bean).afterPropertiesSet();
                   return null;
                }, getAccessControlContext());
             }
             catch (PrivilegedActionException pae) {
                throw pae.getException();
             }
          }
          else {
    //调用InitializingBean的afterPropertiesSet方法
             ((InitializingBean) bean).afterPropertiesSet();
          }
       }
    //如果@Bean中定义了initMethod时,并且initMethod的方法名称不为afterPropertiesSet
       if (mbd != null && bean.getClass() != NullBean.class) {
          String initMethodName = mbd.getInitMethodName();
          if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
             invokeCustomInitMethod(beanName, bean, mbd);
          }
       }
    }
    

    相关文章

      网友评论

        本文标题:spring源码分析3

        本文链接:https://www.haomeiwen.com/subject/cnhxiltx.html