zoukankan      html  css  js  c++  java
  • Spring之IOC容器的依赖注入

    一.Bean的创建 

    bean是什么时候创建的?第一次getBean的时候

    1)检查bean是否已经存在,根据beanName获取BeanDefinition,递归获取依赖bean,根据不同属性的bean调用方法创建bean(如Singleton的,Scope的,Property的)

    //实际获取bean的地方,也是依赖注入的地方
    protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
            String beanName = this.transformedBeanName(name);
          //1检查bean是否已经存在,从缓存中获取已经存在的单例bean,已经存在的bean无需再次创建
            Object sharedInstance = this.getSingleton(beanName);
            Object bean;
            if (sharedInstance != null && args == null) {
                     bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
            } else {
                if (this.isPrototypeCurrentlyInCreation(beanName)) {
                    throw new BeanCurrentlyInCreationException(beanName);
                }
    
               //2 检查BeanDefinition ,检查是否能在当前的BeanFactory 中获取需要的bean,如果获取不到则获取parent,获取不到则一直向上查找,直到获取到
                BeanFactory parentBeanFactory = this.getParentBeanFactory();
                if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
                    String nameToLookup = this.originalBeanName(name);
                    if (parentBeanFactory instanceof AbstractBeanFactory) {
                        return ((AbstractBeanFactory)parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
                    }
    
                    if (args != null) {
                        return parentBeanFactory.getBean(nameToLookup, args);
                    }
    
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
    
                   try {
                 //3 根据beanName获取BeanDefinition
                    RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
                    this.checkMergedBeanDefinition(mbd, beanName, args);
                  //4 获取当前bean依赖的bean,触发递归getBean的获取
                    String[] dependsOn = mbd.getDependsOn();
                    String[] var11;
                    if (dependsOn != null) {
                        var11 = dependsOn;
                        int var12 = dependsOn.length;
    
                        for(int var13 = 0; var13 < var12; ++var13) {
                            String dep = var11[var13]; 
                          this.registerDependentBean(dep, beanName);
                     
              //获取所有依赖的bean
                                this.getBean(dep);
                           
                        }
                    }
                       //bean的创建
           //Singleton bean的创建
                    if (mbd.isSingleton()) {
                        sharedInstance = this.getSingleton(beanName, () -> {
                         
                                return this.createBean(beanName, mbd, args);
                           
                        });
                        bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            //Prototype bean的创建
                    } else if (mbd.isPrototype()) {
                        var11 = null;
                        Object prototypeInstance;
                       
                            this.beforePrototypeCreation(beanName);
                            prototypeInstance = this.createBean(beanName, mbd, args);
               
                    } else {
                        String scopeName = mbd.getScope();
                        Scope scope = (Scope)this.scopes.get(scopeName);
                      
                            Object scopedInstance = scope.get(beanName, () -> {
                                this.beforePrototypeCreation(beanName);
     
                                    var4 = this.createBean(beanName, mbd, args);
                              
                                return var4;
                            });
                     
                         
                    }
                } catch (BeansException var26) {
               
                }
            }
    
           
        } 
    doGetBean

    2)检查循环引用,设置bean的属性

    // 创建bean
     protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
          
            RootBeanDefinition mbdToUse = mbd;
               //1 判断要创建的bean是否可以实例化,可以通过类装载器来载入
            Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
            if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
                mbdToUse = new RootBeanDefinition(mbd);
                mbdToUse.setBeanClass(resolvedClass);
            }
         try {
                 //创建bean的调用
                beanInstance = this.doCreateBean(beanName, mbdToUse, args);
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Finished creating instance of bean '" + beanName + "'");
                }
    
                return beanInstance;
            } 
        }
    
    // 实际创建bean的方法doCreateBean
        protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
            BeanWrapper instanceWrapper = null;
            //如果是单例,则删除缓存中已经存在的同名的bean
            if (mbd.isSingleton()) {
                instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
            }
    
            if (instanceWrapper == null) { 
                 //创建bean
                instanceWrapper = this.createBeanInstance(beanName, mbd, args);
            }
    
            Object bean = instanceWrapper.getWrappedInstance();
            Class<?> beanType = instanceWrapper.getWrappedClass();
           
          //bean 循环引用 
            boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
            if (earlySingletonExposure) {
              
              //循环引用的bean 放入到addSingletonFactory
                this.addSingletonFactory(beanName, () -> {
                    return this.getEarlyBeanReference(beanName, mbd, bean);
                });
            }
    
            Object exposedObject = bean;
    
            try {
               //bean 初始化 ,依赖注入
                this.populateBean(beanName, mbd, instanceWrapper);
                 //exposedObject  做为依赖注入完成后的bean返回
                exposedObject = this.initializeBean(beanName, exposedObject, mbd);
            } catch (Throwable var18) {
               
            }
    
            try {
                this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
                return exposedObject;
            } catch (BeanDefinitionValidationException var16) { 
            }
        }    
    createBean

    3)通过不同的方式创建bean,策略模式,默认SimpleInstantiationStrategy,提供两种实例化方式,一种是BeanUtils(使用JVM的反射功能),另外一种是Cglib(字节码生成类库)

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
              //确认需要创建bean的实例的类可以实例化
            Class<?> beanClass = this.resolveBeanClass(mbd, beanName, new Class[0]);        
                Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
                if (instanceSupplier != null) {
                    return this.obtainFromSupplier(instanceSupplier, beanName);
                } else if (mbd.getFactoryMethodName() != null) {
                   //使用工厂方法对bean进行实例化
                    return this.instantiateUsingFactoryMethod(beanName, mbd, args);
                } else {
                   //构造函数
                    boolean resolved = false;
                    boolean autowireNecessary = false;
                    if (args == null) {
                        Object var8 = mbd.constructorArgumentLock;
                        synchronized(mbd.constructorArgumentLock) {
                            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                                resolved = true;
                                autowireNecessary = mbd.constructorArgumentsResolved;
                            }
                        }                
    
                    if (resolved) {
                   //使用默认的构造函数对bean进行实例化
                        return autowireNecessary ? this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null) : this.instantiateBean(beanName, mbd);
                    } else {
                       //使用构造函数对bean进行实例化
                        Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
                        return ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args) ? this.instantiateBean(beanName, mbd) : this.autowireConstructor(beanName, mbd, ctors, args);
                    }
                }
            }
        }
    
    //instantiateBean 实例化bean
    protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
            try {
                Object beanInstance;
                if (System.getSecurityManager() != null) {
                    //使用默认的实例化策略,对Bean进行实例化默认的是Cglib策略
                    beanInstance = AccessController.doPrivileged(() -> {
                        return thisx.getInstantiationStrategy().instantiate(mbd, beanName, this);
                    }, this.getAccessControlContext());
                } else {
                    beanInstance = this.getInstantiationStrategy().instantiate(mbd, beanName, this);
                }
    
                BeanWrapper bw = new BeanWrapperImpl(beanInstance);
                this.initBeanWrapper(bw);
                return bw;
            } catch (Throwable var6) { 
            }
        }
    
    //  CglibSubclassingInstantiationStrategy  instantiate
    public Object instantiate(@Nullable Constructor<?> ctor, @Nullable Object... args) {
                Class<?> subclass = this.createEnhancedSubclass(this.beanDefinition);
                Object instance;
                if (ctor == null) {
                    instance = BeanUtils.instantiateClass(subclass);
                } else {
                    try {
                        Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
                     //Cglib:创建子类,重写父类方法
                        instance = enhancedSubclassConstructor.newInstance(args);
                    } catch (Exception var6) {
                    
                    }
                }
    
         
                return instance;
            }
    
    //SimpleInstantiationStrategy  instantiate
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
           //通过BeanUtils进行实例化,这个BeanUtils是通过t通过构造函数来实例化的
                return BeanUtils.instantiateClass(constructorToUse, new Object[0]);
            } else {
              //通过Cglib来实例化
                return this.instantiateWithMethodInjection(bd, beanName, owner);
            }
        }
    
    //实际创建bean的地方 : BeanUtils.instantiateClass
     public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
            Assert.notNull(ctor, "Constructor must not be null");
            try {
                ReflectionUtils.makeAccessible(ctor);
                return KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ? BeanUtils.KotlinDelegate.instantiateClass(ctor, args) :
    //创建bean
     ctor.newInstance(args);
            } catch (InstantiationException var3) {
               
        }
    createBeanInstance

    4)属性注入如@Autowired等

    //属性依赖注入入口
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
                 //获取属性
                if (continueWithPropertyPopulation) {
                    PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;
                         //autowire 注入,根据bean名称
                        if (mbd.getResolvedAutowireMode() == 1) {
                            this.autowireByName(beanName, mbd, bw, newPvs);
                        }
                          //autowire 注入,根据bean类型
                        if (mbd.getResolvedAutowireMode() == 2) {
                            this.autowireByType(beanName, mbd, bw, newPvs);
                        }
    
                        pvs = newPvs;
                    }
    
                    //为依赖注入做准备: 解析property 属性 如list ,map ,set 等解析
                    if (pvs != null) {
                        this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
                    }
    
                }
            }
        }
    //真正的 依赖注入
      bw.setPropertyValues
    属性注入populateBean

    二.实例化Bean的策略

    1.Cglib

    三.Bean创建流程

      

  • 相关阅读:
    linux:centOs7换源阿里云
    nginx:负载均衡实战(一)
    linux-安装jdk以及tomcat
    nginx:在linux上进行nginx的安装
    开源 免费 java CMS
    使用PHP获取汉字的拼音(全部与首字母)
    php版获取重定向后地址的代码分享
    php获取数组中重复数据的两种方法
    php删除html标签的三种解决方法
    php curl 伪造IP来源的代码分享
  • 原文地址:https://www.cnblogs.com/fanBlog/p/12674321.html
Copyright © 2011-2022 走看看