spering getBean()

IOC:前面都是对bean定义的处理,postProcess已经实例化了。
解析bean的时候,把需要依赖注入的字段和方法,在postProcessMergedBeanDefinition方法中加到AutowiredAnnotationBeanPostProcessor的变量中,然后在AutowiredAnnotationBeanPostProcessor的作为入口,去依赖注入字段和方法。

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
            beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));  // 实例化一个转换器ConversionService
        }
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
            getBean(weaverAwareName);   //  没用,
        }
        beanFactory.preInstantiateSingletons();  //IOC
    }

public void preInstantiateSingletons() throws BeansException {
        List<String> beanNames;
        synchronized (this.beanDefinitionMap) {   //所有的beanDefinition,也就是bean的定义信息
            beanNames = new ArrayList<String>(this.beanDefinitionNames);  //所有的bean的名字
        }
        for (String beanName : beanNames) {//实例化所有的bean
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);  // 合并功能,父子合并了的。
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {  //不是抽象的,不是懒加载的,是单利,才会去实例化。
                if (isFactoryBean(beanName)) {//实现了FactoryBean接口
                    final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {//实现了SmartFactoryBean接口
                        isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                            @Override
                            public Boolean run() {
                                return ((SmartFactoryBean<?>) factory).isEagerInit();  //调用这个bean的isEagerInit方法,返回true就实例化,
                            }
                        }, getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit()); //调用这个bean的isEagerInit方法,返回true就实例化,
                    }
                    if (isEagerInit) {//返回true就实例化,
                        getBean(beanName); //实例化
                    }
                }
                else {//没有实现了FactoryBean接口,
                    getBean(beanName);
                }
            }
        }
    }

解析有父类的bean,就是合并子类和父类的信息,涉及到子类覆盖父类。

 protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
        RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);  // 先从缓存中拿
        if (mbd != null) {
            return mbd;
        }
        return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
    }

    <bean id="parent" class="com.zhuguang.jack.testbean.Parent" abstract="true">
    </bean>
    <bean id="son" class="com.zhuguang.jack.testbean.Son" parent="parent">
    </bean>    父类是用来继承的公共部分,不会被实例化。

protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd, BeanDefinition containingBd)throws BeanDefinitionStoreException {//beanName是bean的名字,bd是bean的定义

        synchronized (this.mergedBeanDefinitions) {  //mergedBeanDefinitions 是缓存,
            RootBeanDefinition mbd = null;
            if (containingBd == null) {
                mbd = this.mergedBeanDefinitions.get(beanName);
            }
            if (mbd == null) {
                if (bd.getParentName() == null) { //  bean没有父类,直接初始化一个RootBeanDefinition
                    if (bd instanceof RootBeanDefinition) {
                        mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();  //也是调用 new RootBeanDefinition(bd);
                    }
                    else {
                        mbd = new RootBeanDefinition(bd);//bd是bean的定义信息,mbd是子类,bd是父类,这里做一个拷贝,是为了不污染db,而是使用重新初始化的mbd。
                    }
                }
                else {
                     //  bean有父类,要加载父类的信息
                    BeanDefinition pbd;
                    try {
                        String parentBeanName = transformedBeanName(bd.getParentName());  //获取父亲的名字,
                        if (!beanName.equals(parentBeanName)) {  //跟父的名字不一样,
                            pbd = getMergedBeanDefinition(parentBeanName);  //父类的bean定义,父类在有父类继续调用。
                        }
                    }
                    mbd = new RootBeanDefinition(pbd);   //pbd是父类,构造父类
                    mbd.overrideFrom(bd);//bd是bean的定义信息,mbd是父类,bd是子类,子类覆盖父类的信息,
                }

                if (containingBd == null && isCacheBeanMetadata() && isBeanEligibleForMetadataCaching(beanName)) {
                    this.mergedBeanDefinitions.put(beanName, mbd);  //加到缓存
                }
            }
            return mbd;
        }
    }

getBean(beanName);

protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)throws BeansException {

        final String beanName = transformedBeanName(name);
        Object bean;

        //单利缓存中获取
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            if (isPrototypeCurrentlyInCreation(beanName)) {//已经创建了
                throw new BeanCurrentlyInCreationException(beanName);
            }

            BeanFactory parentBeanFactory = getParentBeanFactory();//父类容器,从父类容器获取bean。
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                String nameToLookup = originalBeanName(name);
                if (args != null) {
                    return (T) parentBeanFactory.getBean(nameToLookup, args);;//父类容器,从父类容器获取bean。
                }
                else {
                    return parentBeanFactory.getBean(nameToLookup, requiredType);;//父类容器,从父类容器获取bean。
                }
            }
            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);//父子合并

                String[] dependsOn = mbd.getDependsOn();//依赖的bean,创建这个bean的时候先要创建哪些bean,
                if (dependsOn != null) {
                    for (String dependsOnBean : dependsOn) {
                        if (isDependent(beanName, dependsOnBean)) {//没有依赖关系
                            throw new BeanCreationException("Circular depends-on relationship between ‘" +
                                    beanName + "‘ and ‘" + dependsOnBean + "‘");
                        }
                        registerDependentBean(dependsOnBean, beanName);//增加依赖关系,
                        getBean(dependsOnBean);//先实例化依赖的bean
                    }
                }

                if (mbd.isSingleton()) {//单利
                    sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                        @Override
                        public Object getObject() throws BeansException {
                            try {
                                return createBean(beanName, mbd, args);
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {//多利
                    // It‘s a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope ‘" + scopeName + "‘");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
                            @Override
                            public Object getObject() throws BeansException {
                                beforePrototypeCreation(beanName);
                                try {
                                    return createBean(beanName, mbd, args);
                                }
                                finally {
                                    afterPrototypeCreation(beanName);
                                }
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                }
            }
        }

        if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
            try {
                return getTypeConverter().convertIfNecessary(bean, requiredType);
            }
        }
        return (T) bean;
    }

单利:
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
    @Override
    public Object getObject() throws BeansException {
        try {
            return createBean(beanName, mbd, args);
        }
    }
});

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        synchronized (this.singletonObjects) {//缓存
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                try {
                    singletonObject = singletonFactory.getObject();  //createBean
                }
                addSingleton(beanName, singletonObject);//缓存
            }
            return (singletonObject != NULL_OBJECT ? singletonObject : null);
        }
    }

protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)throws BeanCreationException {
        resolveBeanClass(mbd, beanName);   //bean的定义,bean的名字,拿出beanClass,
        try {
            mbd.prepareMethodOverrides();
        }
        try {
            Object bean = resolveBeforeInstantiation(beanName, mbd);//BeanPostProcessors已经实例化了,实例化之前插一脚,直接返回这个实例化的bean。后面不用走了。可以自己去实例化这个bean,spring就不会管这个bean的实例化了。下面有梨子InstantiationAwareBeanPostProcessorTest,
            if (bean != null) {
                return bean;
            }
        }
  //前面resolveBeforeInstantiation没有成功实例化出这个bean。spring来实例化这个bean。
        Object beanInstance = doCreateBean(beanName, mbd, args);
        return beanInstance;
    }

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName);
                if (bean != null) {
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);  //先执行before在执行after方法,
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }

protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)throws BeansException {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {  //取出所有的BeanPostProcessors,
            if (bp instanceof InstantiationAwareBeanPostProcessor) {  //  实现InstantiationAwareBeanPostProcessor接口的自己写的类,可以自己去实例化这个bean,spring就不会管这个bean的实例化了。下面有梨子InstantiationAwareBeanPostProcessorTest,
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);  //通过所有的BeanPostProcessors来返回这个实例化的bean。spring就不会管这个bean的实例化了。
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

public class InstantiationAwareBeanPostProcessorTest implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        try {
            return beanClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);//缓存,
        }
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);  // 包装类,通过反射实例创建完成。但是实例的属性还没有操作。不包括IOC的依赖注入。属性是没有值的。
        }
        final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
        Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);   //下面解析,                //解析完这个类需要依赖注入的字段和方法之后,在AutowiredAnnotationBeanPostProcessor增加一行记录factoryBeanTest=[FactoryBeanTest.woman(依赖注入字段), FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)(依赖注入方法)]。
                }
                mbd.postProcessed = true;
            }
        }

        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); // 是单利并且允许循环依赖,
        if (earlySingletonExposure) {
            addSingletonFactory(beanName, new ObjectFactory<Object>() {//把ObjectFactory这个匿名对象加入到spring的三级缓存,在getSingleton从缓存取的时候,会调用三级缓存中的匿名对象ObjectFactory的getObject() 。
                @Override
                public Object getObject() throws BeansException {
                    return getEarlyBeanReference(beanName, mbd, bean);
                }
            });
        }

        Object exposedObject = bean;
        try {
            populateBean(beanName, mbd, instanceWrapper);  //IOC,依赖注入8中类型,
            if (exposedObject != null) {
                exposedObject = initializeBean(beanName, exposedObject, mbd);
            }
        }

        if (earlySingletonExposure) {
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName,");
                    }
                }
            }
        }

        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);  //注册,
        }

        return exposedObject;
    }

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
        Class<?> beanClass = resolveBeanClass(mbd, beanName);//拿到bean的class,class com.zhuguang.jack.testbean.A,
  if (mbd.getFactoryMethodName() != null)  {
            return instantiateUsingFactoryMethod(beanName, mbd, args);  //自己写的类去初始化,不要spring实例化,
         }
        return instantiateBean(beanName, mbd);
    }
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<Object>() {
                    @Override
                    public Object run() {
                        return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                    }
                }, getAccessControlContext());
            }
            else {
                beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);  //通过反射,[email protected]实例创建完成。
            }
            BeanWrapper bw = new BeanWrapperImpl(beanInstance);  //包装,
            initBeanWrapper(bw);
            return bw;
        }
    }

public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
        if (beanDefinition.getMethodOverrides().isEmpty()) {
            synchronized (beanDefinition.constructorArgumentLock) {
                constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
                if (constructorToUse == null) {
                    final Class<?> clazz = beanDefinition.getBeanClass();  //拿到需要实例化的类,
                    try {
                        if (System.getSecurityManager() != null) {
                            constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
                                @Override
                                public Constructor<?> run() throws Exception {
                                    return clazz.getDeclaredConstructor((Class[]) null);  //拿到构造器,无参构造器,为了防止循环依赖问题。
                                }
                            });
                        }
                    }
                }
            }
            return BeanUtils.instantiateClass(constructorToUse);//反射,实例化bean,
        }
else {
            return instantiateWithMethodInjection(beanDefinition, beanName, owner);//Cglib
        }
    }

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)throws BeansException {
        try {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof MergedBeanDefinitionPostProcessor) {//实现这个接口的bean,才能做处理,
                    MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;  //  有一个AutowiredAnnotationBeanPostProcessor,
                    bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
                }
            }
        }
    }

AutowiredAnnotationBeanPostProcessor类的:依赖注入可以通过配置文件,也可以通过注解@Autowired,@Autowired,可以加载属性上面,也可以加载set方法上面。
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        if (beanType != null) {
            InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType); //返回这个类,需要注解依赖注入的属性和方法,
            metadata.checkConfigMembers(beanDefinition);
        }
    }

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz) {
        String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);  //AutowiredAnnotationBeanPostProcessor的缓存,
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            synchronized (this.injectionMetadataCache) {
                metadata = this.injectionMetadataCache.get(cacheKey);
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                    metadata = buildAutowiringMetadata(clazz);  //返回这个类,需要注解依赖注入的属性和方法,
                    this.injectionMetadataCache.put(cacheKey, metadata);  //解析完这个类需要依赖注入的字段和方法之后,在AutowiredAnnotationBeanPostProcessor增加一行记录factoryBeanTest = [ FactoryBeanTest.woman, FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)],this=AutowiredAnnotationBeanPostProcessor。
                }
            }
        }
        return metadata;
    }
private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
        LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
        Class<?> targetClass = clazz;

        do {
            LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();  //InjectedElement是反射的属性或者方法对象,
   //@Autowired加载属性上面,
            for (Field field : targetClass.getDeclaredFields()) { //  拿到类的所有属性,
                AnnotationAttributes annotation = findAutowiredAnnotation(field);  //获取字段的Autowired,Value,Inject 3种注解,其余注解不管,返回映射关系,
                if (annotation != null) {
                    if (Modifier.isStatic(field.getModifiers())) {
                        continue;
                    }
                    boolean required = determineRequiredStatus(annotation);//拿到注解的值,
                    currElements.add(new AutowiredFieldElement(field, required));  //一个字段field对应一个AutowiredFieldElement,装到容器中。还没有涉及到IOC过程。
                }
            }
   //@Autowired加载set方法上面,
            for (Method method : targetClass.getDeclaredMethods()) { //  拿到类的所有方法,有注解的方法是                              FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)。
@Autowired
public void setWoman(Woman woman) {
this.woman = woman;
 },
                Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);  //方法的重载
                AnnotationAttributes annotation = BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod) ?
                        findAutowiredAnnotation(bridgedMethod) : findAutowiredAnnotation(method);  //找到这个方法上面有没有Autowired,Value,Inject 3种注解,其余注解不管,
                if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        continue;
                    }
                    boolean required = determineRequiredStatus(annotation);//拿到注解的值,
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);//拿到方法的类型对象PropertyDescriptor
                    currElements.add(new AutowiredMethodElement(method, required, pd));//把method, required, pd包装成AutowiredMethodElement放到容器currElements中去,
                }
            }
            elements.addAll(0, currElements);
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null && targetClass != Object.class);  //父类,也去解析父类,
        return new InjectionMetadata(clazz, elements);  //返回这个类,需要注解依赖注入的属性和方法,
    }

public AutowiredAnnotationBeanPostProcessor() {   //AutowiredAnnotationBeanPostProcessor里面加了Autowired,Value,Inject 3种注解,
        this.autowiredAnnotationTypes.add(Autowired.class);
        this.autowiredAnnotationTypes.add(Value.class);
        ClassLoader cl = AutowiredAnnotationBeanPostProcessor.class.getClassLoader();
        this.autowiredAnnotationTypes.add((Class<? extends Annotation>) cl.loadClass("javax.inject.Inject"));
    }

singletonObjects是一级缓存,一个bean依赖注入完成之后,属性都完成了,才会存在在singletonObjects这个Map里面。
earlySingletonObjects是二级缓存,一个bean还没有完全实例化,有可能里面还有一些属性,还没有完全依赖注入完。
singletonFactories是三级缓存,里面存的是ObjectFactory对象。

二级三级缓存,就是为了解决循环依赖问题,A里面有B,B里面有A。A实例化的时候B没有实例化,此时A还是一个空壳子,会加到三级缓存,然后getBean(B),B实例化的时候发现有属性A,会去实例化getBean(A),此时A在三级缓存中,会调用这个三级缓存的getObject()方法。

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);//从第一级取
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);//从第二级取
                if (singletonObject == null && allowEarlyReference) {
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);//从第三级取
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();  //三级缓存调用getObject(),
                        this.earlySingletonObjects.put(beanName, singletonObject);//移到二级缓存,
                        this.singletonFactories.remove(beanName);//从三级缓存删除,
                    }
                }
            }
        }
return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }

protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
        synchronized (this.singletonObjects) {
            if (!this.singletonObjects.containsKey(beanName)) {//一级缓存没有
                this.singletonFactories.put(beanName, singletonFactory);//放入三级缓存,准备上面的,调用三级缓存的getObject(),
                this.earlySingletonObjects.remove(beanName);//二级缓存移除
                this.registeredSingletons.add(beanName);
            }
        }
    }

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
        Object exposedObject = bean;
        if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {  //这个接口,
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                    exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                    if (exposedObject == null) {
                        return exposedObject;
                    }
                }
            }
        }
        return exposedObject;
    }

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
        PropertyValues pvs = mbd.getPropertyValues();  //拿到factoryBeanTest的需要依赖注入的属性,PropertyValues: length=1; bean property ‘woman‘
        boolean continueWithPropertyPopulation = true;  //当前bean的依赖注入到底要不要做,
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {  //
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {   //返回布尔值,当前bean的依赖注入要不要做,
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }
        if (!continueWithPropertyPopulation) {   //为false,当前bean的依赖注入就不用做了,
            return;
        }
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();  //有没有实现InstantiationAwareBeanPostProcessor接口,
        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) {  //找到这个接口的类,包括spring的和自己的,
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);//@Autoware,@Value的依赖注入。   AutowiredAnnotationBeanPostProcessor类的postProcessPropertyValues方法,依赖注入在这里。
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
        }
        applyPropertyValues(beanName, mbd, bw, pvs);   //通过xml依赖注入,
    }

AutowiredAnnotationBeanPostProcessor类:
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass());  //从缓存取,需要依赖注入的字段和方法,[FactoryBeanTest.woman, .FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)],
        try {
            metadata.inject(bean, beanName, pvs);//依赖注入在这里。
        }
        return pvs;
    }

public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {
        Collection<InjectedElement> elementsToIterate = (this.checkedElements != null ? this.checkedElements : this.injectedElements); //[FactoryBeanTest.woman, FactoryBeanTest.setWoman(com.zhuguang.jack.testbean.Woman)],
        if (!elementsToIterate.isEmpty()) {
            for (InjectedElement element : elementsToIterate) {
                element.inject(target, beanName, pvs);  //目标对象[email protected],bean名字factoryBeanTest,需要依赖注入的字段或者方法[bean property ‘woman‘]  。依赖注入在这里。
            }
        }
    }

//依赖注入字段。依赖注入在这里。
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
            Field field = (Field) this.member;  //FactoryBeanTest.woman
            try {
                Object value;
                if (this.cached) {
                    value = resolvedCachedArgument(beanName, this.cachedFieldValue);
                }
                else {
                    DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
                    desc.setContainingClass(bean.getClass());
                    Set<String> autowiredBeanNames = new LinkedHashSet<String>(1);
                    TypeConverter typeConverter = beanFactory.getTypeConverter();
                    value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);//拿到依赖注入的属性的值,[email protected]。
                    synchronized (this) {
                        if (!this.cached) {
                            if (value != null || this.required) {
                                this.cachedFieldValue = desc;
                                registerDependentBeans(beanName, autowiredBeanNames);
                            }
                            this.cached = true;
                        }
                    }
                }
                if (value != null) {//[email protected],
                    ReflectionUtils.makeAccessible(field);
                    field.set(bean, value);   //字段设置值
                }
            }
        }
    }

public Object resolveDependency(DependencyDescriptor descriptor, String beanName,
            Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
        else {
            if (result == null) {
                result = doResolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
            }
            return result;//[email protected]。
        }
    }

public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
            Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

        Class<?> type = descriptor.getDependencyType();  //class com.zhuguang.jack.testbean.Woman
        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        if (value != null) {
            if (value instanceof String) {
                String strVal = resolveEmbeddedValue((String) value);
                BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
                value = evaluateBeanDefinitionString(strVal, bd);
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return (descriptor.getField() != null ?
                    converter.convertIfNecessary(value, type, descriptor.getField()) :
                    converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
        }

        if (type.isArray()) {  //依赖注入的是数组
            Class<?> componentType = type.getComponentType();
            DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
            targetDesc.increaseNestingLevel();
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, targetDesc);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            Object result = converter.convertIfNecessary(matchingBeans.values(), type);
            if (this.dependencyComparator != null && result instanceof Object[]) {
                Arrays.sort((Object[]) result, this.dependencyComparator);
            }
            return result;
        }
        else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { //依赖注入的是集合
            Class<?> elementType = descriptor.getCollectionType();
            if (elementType == null) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]");
                }
                return null;
            }
            DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
            targetDesc.increaseNestingLevel();
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, targetDesc);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            Object result = converter.convertIfNecessary(matchingBeans.values(), type);
            if (this.dependencyComparator != null && result instanceof List) {
                Collections.sort((List<?>) result, this.dependencyComparator);
            }
            return result;
        }
        else if (Map.class.isAssignableFrom(type) && type.isInterface()) { //依赖注入的是MAp
            Class<?> keyType = descriptor.getMapKeyType();
            if (keyType == null || !String.class.isAssignableFrom(keyType)) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
                            "] must be assignable to [java.lang.String]");
                }
                return null;
            }
            Class<?> valueType = descriptor.getMapValueType();
            if (valueType == null) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("No value type declared for map [" + type.getName() + "]");
                }
                return null;
            }
            DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
            targetDesc.increaseNestingLevel();
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, targetDesc);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            return matchingBeans;
        }
        else {  //依赖注入不是数组,不是Map,不是集合,是基本类型或者对象,
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);  //{[email protected]},从bean工厂获取,最终还是通过getBean()方法获取。
if (matchingBeans.size() > 1) {//依赖注入的类有多个,报错。
                String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor);
                if (primaryBeanName == null) {
                    throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
                }
                if (autowiredBeanNames != null) {
                    autowiredBeanNames.add(primaryBeanName);
                }
                return matchingBeans.get(primaryBeanName);
            }
            Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
            if (autowiredBeanNames != null) {
                autowiredBeanNames.add(entry.getKey());
            }
            return entry.getValue();//[email protected]
        }
    }

protected Map<String, Object> findAutowireCandidates(
            String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {

        for (String candidateName : candidateNames) {
            if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) {
                result.put(candidateName, getBean(candidateName));  //还是通过getBean()方法获取需要依赖注入的属性的值,
            }
        }
        return result;
    }

//方法的依赖注入,依赖注入在这里。通过反射给方法设置值,形参通过getBean()方法获取。
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
                else {
                        Object arg = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
                        if (arg == null && !this.required) {
                            arguments = null;
                            break;
                        }
                        arguments[i] = arg;
                    }
                }
                if (arguments != null) {
                    ReflectionUtils.makeAccessible(method);
                    method.invoke(bean, arguments);   //通过反射给方法设置值,形参通过getBean()方法获取。
                }
            }
        }

上main是通过注解的依赖注入,还有通过XML的依赖注入。

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {   //通过xml依赖注入,

        MutablePropertyValues mpvs = null;
        List<PropertyValue> original;

        if (System.getSecurityManager() != null) {
            if (bw instanceof BeanWrapperImpl) {
                ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
            }
        }

        if (pvs instanceof MutablePropertyValues) {
            mpvs = (MutablePropertyValues) pvs;
            if (mpvs.isConverted()) {
                try {
                    bw.setPropertyValues(mpvs);
                    return;
                }
            }
            original = mpvs.getPropertyValueList();  //[bean property ‘woman‘],需要xml依赖注入的属性,
        }
        else {
            original = Arrays.asList(pvs.getPropertyValues());   //[bean property ‘woman‘],需要xml依赖注入的属性,
        }

        TypeConverter converter = getCustomTypeConverter();
        if (converter == null) {
            converter = bw;
        }
        BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

        List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
        boolean resolveNecessary = false;
        for (PropertyValue pv : original) {
            else {
                String propertyName = pv.getName();//woman,
                Object originalValue = pv.getValue();//<woman>,RuntimeBeanReference类型,
                Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);  //beanFactory.getBean(refName);从bean工厂拿。因为依赖注入的属性有可能是一个引用,有可能是一个字符串需要转换成时间,
                Object convertedValue = resolvedValue;  //[email protected],
                boolean convertible = bw.isWritableProperty(propertyName) &&!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
                if (convertible) {
                    convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);//[email protected],类型转换之后的值。上面的valueResolver.resolveValueIfNecessary(pv, originalValue)有可能转换还不够,还需要转换,
                }
                if (resolvedValue == originalValue) {
                    if (convertible) {
                        pv.setConvertedValue(convertedValue);
                    }
                    deepCopy.add(pv);
                }
                else if (convertible && originalValue instanceof TypedStringValue &&
                        !((TypedStringValue) originalValue).isDynamic() &&
                        !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                    pv.setConvertedValue(convertedValue);
                    deepCopy.add(pv);
                }
                else {
                    resolveNecessary = true;
                    deepCopy.add(new PropertyValue(pv, convertedValue));  //pv, convertedValue一个是原始属性值,一个是转换之后的值。封装成PropertyValue,
                }
            }
        }

        try {
            bw.setPropertyValues(new MutablePropertyValues(deepCopy));  //设置值,MutablePropertyValues才是需要真正设置的值。
        }
    }

public void setPropertyValue(PropertyValue pv) throws BeansException {
        PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
        if (tokens == null) {
            String propertyName = pv.getName();
            BeanWrapperImpl nestedBw;
            try {
                nestedBw = getBeanWrapperForPropertyPath(propertyName);
            }
            tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
            if (nestedBw == this) {
                pv.getOriginalPropertyValue().resolvedTokens = tokens;
            }
            nestedBw.setPropertyValue(tokens, pv);
        }
        else {
            setPropertyValue(tokens, pv);
        }
    }

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            invokeInitMethods(beanName, wrappedBean, mbd);
        }

        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    }

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;
    }

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);
            }
        }
    }

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)throws Throwable {
        boolean isInitializingBean = (bean instanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
            else {
                ((InitializingBean) bean).afterPropertiesSet();   //实例化bean的时候,调用afterPropertiesSet()方法,没有参数,做资源的加载(redis,mongodb的加载,),一个bean只会调用一次。在bean实例化之后,IOC之后调用。
            }
        }

        if (mbd != null) {
            String initMethodName = mbd.getInitMethodName();
            if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) {
                invokeCustomInitMethod(beanName, bean, mbd);
            }
        }
    }

protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable {
        String initMethodName = mbd.getInitMethodName();  //拿到init方法的名称,init-method,
        final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
                BeanUtils.findMethod(bean.getClass(), initMethodName) :
                ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));   //反射得到这个方法,
        else {
            try {
                ReflectionUtils.makeAccessible(initMethod);
                initMethod.invoke(bean);   //调用,
            }
        }
    }

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
            if (mbd.isSingleton()) {  //单利,就缓存,
                registerDisposableBean(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
            else {
                Scope scope = this.scopes.get(mbd.getScope());
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope ‘" + mbd.getScope() + "‘");
                }
                scope.registerDestructionCallback(beanName,
                        new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
        }
    }

public void registerDisposableBean(String beanName, DisposableBean bean) {
        synchronized (this.disposableBeans) {
            this.disposableBeans.put(beanName, bean);
        }
    }

原文地址:https://www.cnblogs.com/yaowen/p/11728275.html

时间: 2024-11-09 01:58:51

spering getBean()的相关文章

解决solrj getBean和getBeans出错

由于使用SolrJ自带的addBean和addBeans老是出现了org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object of class com.study.model.SolrItem 然后发现是Solr添加数据的时候加多了个_version_的问题 为了解决这个问题,采用的如下的方法 /** * SolrUtil帮助类 能够将SolrDocument转换为Java对象 * @Titl

Spring杂记BeanFactory之getBean方法

1.(BeanFactory) getBean(beanName) 2.(AbstractBeanFactory) doGetBean 3.(AbstractBeanFactory) transformedBeanName //如果是&beanName工厂类形式去掉第一个& 4.(AbstractBeanFactory) getSingleton 5.(DefaultSingletonBeanRegistry) getSingleton //从Map<String, Object&g

2.1.2_BeanFactory.getBean内部处理逻辑

在一个已经注册了BeanDefinition的BeanFactory中,通过getBean方法就可以获取到对应的Bean对象,但BeanFactory的内部处理逻辑还是非常复杂,主要的工作可以分为getBean和createBean两部分,下面以DefaultListableBeanFactory为例来说明. getBean阶段: 1.DefaultListableBeanFactory本身继承了DefaultSingletonBeanRegistry类,内部持有已经创建的Singleton的实

applicationContext.getBean(“loginEntity”)

<!-- 指定Spring需要扫描的包,并将所有是别的类放到容器中,便于识别被注解的受托管bean --> <context:component-scan base-package="com.sgfm" scoped-proxy="interfaces"> <context:exclude-filter type="regex" expression="com.sgfm.base.jms.demo.*&qu

关于spring获取webApplication.getBean多种途径和简单解释

ApplicationContext ac1 = new FileSystemXmlApplicationContext("com/spark/system/applicationContext.xml");//如果配置文件放在文件系统的目录下则优先使用该方式 //com/spark/system/applicationContext.xml等价于"file:com/spark/system/applicationContext.xml" ac1.getBean(&

Spring在web应用中获得Bean的方法 实现getBean方法

1.新建类,并实现 org.springframework.context.ApplicationContextAware 接口. package com.abc.framework.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationCo

spring getbean 方法分析

spring 缺省: 1.spring用DefaultListableBeanFactory.preInstantiateSingletons()建立bean实例 2.缺省采用单例模式 在最近的项目中,有个地方我们不得不实用getBean的方法,自己从Spring context中获取bean进行数据库操作. 方法一(效率低,极易出现bug,不推荐使用): 刚刚开始的时候,我们使用这中方式,但是在应用过程中发现此方式效率低下,而且极易出现bug. 在我们系统中会生成ehcache_auto_cr

模拟Spring容器的getBean方法(Maven工程)

Spring容器的getBean方法是通过反射机制实现的,下面的测试程序模拟getBean的实现原理. 步骤一:pom.xml文件配置解析XML文件的dom4j.jar 步骤二:XML文件中配置bean标签 步骤三:创建测试类ParseSpringXMLTest,设置成员属性,由于bean标签中没有设置Scope属性,故默认使用singleton创建单例.这里创建一个Map集合保存创建好的对象. 步骤四:创建构造器,初始化成员属性 步骤五:模拟实现getBean方法 步骤六:测试程序 步骤七:控

spring 的 ApplicationContext.getBean(type) 无法获取bean,报错

具体问题请看   https://q.cnblogs.com/q/108101/ 研究了两天: 经过上文中的排除法: 造成问题的原因是要获取的bean 中 有被切入的方法.. 就是可能该类会使用反射生成一个类.. 怎么测试呢? 想到 @Autowired  和 @Resource  这两个注解.. 他们会通过 类型 和 名称去找容器中对应 的 bean .. 于是在controller 中使用 这个注解 注入 zaService; 报错了  : Caused by: org.springfram