美文网首页
spring如何进行bean的实例化(二)依赖注入

spring如何进行bean的实例化(二)依赖注入

作者: guessguess | 来源:发表于2020-06-29 11:37 被阅读0次

    上一篇中只大致讲了如何实例化的过程,但是循环依赖是如何解决的并没有讲到,这里粗略来讲解一下。
    https://www.jianshu.com/writer#/notebooks/44580062/notes/71832204

    顺着上一篇,先回到AbstractAutowireCapableBeanFactory的createBean方法
    看上去虽然只有2个方法,其实代码量是挺大的
    我们需要关注一个类org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor,看这个名字大家应该猜到它是做什么的了,就是后置处理@Autowired注解的
    另外的话需要关注一个方法populateBean这个方法,这个方法就是获取 依赖注入的缓存信息,进行依赖注入的相关信息。

    因为有点不太好看 所以用debug的方式吧,先添加下面几个类

    @Controller
    @RequestMapping(value = "/hello")
    public class HelloController {
        @Autowired
        private HelloService helloService;
    }
    
    @Service
    public class HelloServiceImp implements HelloService{
    
        @Override
        public String sayHello() {
            return "say hello";
        }
    
    }
    
    public interface HelloService {
        public String sayHello();
    }
    

    测试方法

    @Configuration
    @ComponentScan(basePackages = "com.gee")
    public class Config {
        
        public static void main(String args[]) {
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
            for(String str : applicationContext.getBeanDefinitionNames()) {
                System.out.println(str);
            }
        }
    }
    

    一开始会经历我们上篇文章所说到的方法
    下面的话,目光锁定在AbstractAutowireCapableBeanFactory的createBean方法

    public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
            implements AutowireCapableBeanFactory {
     */
        @Override
        protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
                throws BeanCreationException {
    
            if (logger.isDebugEnabled()) {
                logger.debug("Creating instance of bean '" + beanName + "'");
            }
            RootBeanDefinition mbdToUse = mbd;
    
            // Make sure bean class is actually resolved at this point, and
            // clone the bean definition in case of a dynamically resolved Class
            // which cannot be stored in the shared merged bean definition.
            Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
            if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
                mbdToUse = new RootBeanDefinition(mbd);
                mbdToUse.setBeanClass(resolvedClass);
            }
    
            // Prepare method overrides.
            try {
                mbdToUse.prepareMethodOverrides();
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                        beanName, "Validation of method overrides failed", ex);
            }
    
            try {
                // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
                //这里就是给用户提供一个机会通过后置处理器去返回代理对象,这里面其实也是找到后置处理器的实现类,然后执行获取返回值,这里因为本身没有去实现对应接口,所以当然没有值
                Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
                if (bean != null) {
                    return bean;
                }
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                        "BeanPostProcessor before instantiation of bean failed", ex);
            }
    
            try {
                //创建bean,直接进入该方法
                Object beanInstance = doCreateBean(beanName, mbdToUse, args);
                if (logger.isDebugEnabled()) {
                    logger.debug("Finished creating instance of bean '" + beanName + "'");
                }
                return beanInstance;
            }
            catch (BeanCreationException ex) {
                // A previously detected exception with proper bean creation context already...
                throw ex;
            }
            catch (ImplicitlyAppearedSingletonException ex) {
                // An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry...
                throw ex;
            }
            catch (Throwable ex) {
                throw new BeanCreationException(
                        mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
            }
        }
    
        protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
                throws BeanCreationException {
            BeanWrapper instanceWrapper = null;
            //判断是否为单例
            if (mbd.isSingleton()) {
                //若为单例,首先看看缓存中是否存在对应的FactoryBean
                instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
            }
            //若缓存不存在,则直接创建
            if (instanceWrapper == null) {
                 //创建beanInstance,方法很复杂,其实最后就是通过mbd的class进行反射,获取实例
                instanceWrapper = createBeanInstance(beanName, mbd, args);
            }
            final Object bean = instanceWrapper.getWrappedInstance();
            Class<?> beanType = instanceWrapper.getWrappedClass();
            if (beanType != NullBean.class) {
                mbd.resolvedTargetType = beanType;
            }
    
            // Allow post-processors to modify the merged bean definition.
            synchronized (mbd.postProcessingLock) {
                if (!mbd.postProcessed) {
                    try {
                       //bean的后置处理器执行->这里有一个重点,就是关于依赖注入的,创建该类的依赖注入信息,比如这个类下,依赖注入的信心,直接往下走看看是怎么执行的
                        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                    }
                    catch (Throwable ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Post-processing of merged bean definition failed", ex);
                    }
                    mbd.postProcessed = true;
                }
            }
    
            // 为了解决循环依赖,所以允许缓存提前被使用
            boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                    isSingletonCurrentlyInCreation(beanName));
            if (earlySingletonExposure) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Eagerly caching bean '" + beanName +
                            "' to allow for resolving potential circular references");
                }
                 //将创建后的bean加入第三级缓存中
                addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
            }
    
            // Initialize the bean instance.
            Object exposedObject = bean;
            try {
                //解决循环依赖,后面再讲
                populateBean(beanName, mbd, instanceWrapper);
                exposedObject = initializeBean(beanName, exposedObject, mbd);
            }
            catch (Throwable ex) {
                if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                    throw (BeanCreationException) ex;
                }
                else {
                    throw new BeanCreationException(
                            mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
                }
            }
    
            if (earlySingletonExposure) {
                //再次从缓存中获取实例,以一级二级缓存的例子为准,因为传了false,所以不会读取第三级缓存
                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<>(dependentBeans.length);
                        for (String dependentBean : dependentBeans) {
                            if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                                actualDependentBeans.add(dependentBean);
                            }
                        }
                        if (!actualDependentBeans.isEmpty()) {
                            throw new BeanCurrentlyInCreationException(beanName,
                                    "Bean with name '" + beanName + "' has been injected into other beans [" +
                                    StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                    "] in its raw version as part of a circular reference, but has eventually been " +
                                    "wrapped. This means that said other beans do not use the final version of the " +
                                    "bean. This is often the result of over-eager type matching - consider using " +
                                    "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                        }
                    }
                }
            }
    
            // Register bean as disposable.
            try {
                registerDisposableBeanIfNecessary(beanName, bean, mbd);
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
            }
    
            return exposedObject;
        }
    
        protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
            //其实又是一个很熟悉的模式,责任链模式,这个时候我们需要关注org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof MergedBeanDefinitionPostProcessor) {
                    MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                    //当遍历到AutowiredAnnotationBeanPostProcessor这个后置处理器的时候,直接进去,看看如何处理的。
                    bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
                }
            }
        }
    }
    

    如何生成依赖注入的元数据

    public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
            implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
        @Override
        public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
            //创建依赖注入的元数据缓存信息,直接进入该方法
            InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
            metadata.checkConfigMembers(beanDefinition);
        }
    
        private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
            String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
            //根据类名从缓存中获取依赖注入的缓存信息
            InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
           //这里说的需要刷新,指的是当缓存信息对应的目标类与cacheKey不一致时,亦或者缓存不存在时,因为上面用到了InjectionMetadata这个类,所以就讲一下这个类的结构吧
           /**public class InjectionMetadata {
                    private final Class<?> targetClass;表示依赖注入缓存对应的类
                    private final Collection<InjectedElement> injectedElements;依赖注入的所有元素集合
             }
            public static abstract class InjectedElement {
                    protected final Member member;成员,成员中记载了对应类的信息
                    protected final boolean isField;是属性或者方法
             }
           **/
            //一开始当然是需要刷新的
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                synchronized (this.injectionMetadataCache) {
                    metadata = this.injectionMetadataCache.get(cacheKey);
                    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                        if (metadata != null) {
                            metadata.clear(pvs);
                        }
                        //创建依赖注入的元数据,看看该方法是如何执行的,直接往里面走
                        metadata = buildAutowiringMetadata(clazz);
                        //并且放入缓存中
                        this.injectionMetadataCache.put(cacheKey, metadata);
                    }
                }
            }
            return metadata;
        }
    
       //说白了,这个方法就是创建依赖注入的元数据
        private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
            LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
            Class<?> targetClass = clazz;
    
            do {
                final LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
                //这里代码就不贴了,比较简单,其实就是遍历该类下所有的field找到被@value跟@autowired修饰的成员遍历,随后添加到currElements中去
                ReflectionUtils.doWithLocalFields(targetClass, field -> {
                    AnnotationAttributes ann = findAutowiredAnnotation(field);
                    if (ann != null) {
                        if (Modifier.isStatic(field.getModifiers())) {
                            if (logger.isWarnEnabled()) {
                                logger.warn("Autowired annotation is not supported on static fields: " + field);
                            }
                            return;
                        }
                        boolean required = determineRequiredStatus(ann);
                        currElements.add(new AutowiredFieldElement(field, required));
                    }
                });
                //方法的话,比较复杂,但是应该也是类似的,这里就略过了
                ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                    Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                    if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                        return;
                    }
                    AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
                    if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                        if (Modifier.isStatic(method.getModifiers())) {
                            if (logger.isWarnEnabled()) {
                                logger.warn("Autowired annotation is not supported on static methods: " + method);
                            }
                            return;
                        }
                        if (method.getParameterCount() == 0) {
                            if (logger.isWarnEnabled()) {
                                logger.warn("Autowired annotation should only be used on methods with parameters: " +
                                        method);
                            }
                        }
                        boolean required = determineRequiredStatus(ann);
                        PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                        currElements.add(new AutowiredMethodElement(method, required, pd));
                    }
                });
    
                elements.addAll(0, currElements);
                targetClass = targetClass.getSuperclass();
            }
            while (targetClass != null && targetClass != Object.class);
            //最后返回目标类,以及目标类的依赖元数据
            return new InjectionMetadata(clazz, elements);
        }
    
    }
    
    

    那么下面就是如何利用这些元数据了
    我们接着看就是populateBean 装饰bean的方法了,直接进入populateBean方法看看内部实现

    public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
            implements AutowireCapableBeanFactory {
    
        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;
                }
            }
    
            //这里的话,给用于提供机会自己去完善bean,也是通过实现后置处理器来处理
            boolean continueWithPropertyPopulation = true;
    
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                            continueWithPropertyPopulation = false;
                            break;
                        }
                    }
                }
            }
            //如果后置处理器已经处理过了,则不需要去处理了,直接返回
            if (!continueWithPropertyPopulation) {
                return;
            }
    
            PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
            //这里是xml的处理方式,由于本次使用的是注解的方式,所以先略过
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
                    mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
                MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
    
                // Add property values based on autowire by name if applicable.
                if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
                    autowireByName(beanName, mbd, bw, newPvs);
                }
    
                // Add property values based on autowire by type if applicable.
                if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
                    autowireByType(beanName, mbd, bw, newPvs);
                }
    
                pvs = newPvs;
            }
    
            boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
            boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
    
            if (hasInstAwareBpps || needsDepCheck) {
                if (pvs == null) {
                    pvs = mbd.getPropertyValues();
                }
                PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                if (hasInstAwareBpps) {
                    for (BeanPostProcessor bp : getBeanPostProcessors()) {
                        if (bp instanceof InstantiationAwareBeanPostProcessor) {
                            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                            //org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor只关注这个类的处理方式,直接进入方法内部
                            pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                            if (pvs == null) {
                                return;
                            }
                        }
                    }
                }
                if (needsDepCheck) {
                    checkDependencies(beanName, mbd, filteredPds, pvs);
                }
            }
    
            if (pvs != null) {
                applyPropertyValues(beanName, mbd, bw, pvs);
            }
        }
    }
    

    下面看看AutowiredAnnotationBeanPostProcessor的内部处理

    public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
            implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
        @Override
        public PropertyValues postProcessPropertyValues(
                PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
            //就是从缓存获取依赖元数据
            InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
            try {
                //随后就是进行依赖注入了,看看如何进行的
                metadata.inject(bean, beanName, pvs);
            }
            catch (BeanCreationException ex) {
                throw ex;
            }
            catch (Throwable ex) {
                throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
            }
            return pvs;
        }
    }
    
    public class InjectionMetadata {
        public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
            Collection<InjectedElement> checkedElements = this.checkedElements;
            Collection<InjectedElement> elementsToIterate =
                    (checkedElements != null ? checkedElements : this.injectedElements);
            if (!elementsToIterate.isEmpty()) {
                boolean debug = logger.isDebugEnabled();
                //获取出依赖元素的集合,逐个去注入
                for (InjectedElement element : elementsToIterate) {
                    if (debug) {
                        logger.debug("Processing injected element of bean '" + beanName + "': " + element);
                    }
                    //这个方法便是注入,那么直接进去便是
                    element.inject(target, beanName, pvs);
                }
            }
        }
    }
    

    看看是如何进行注入的

    private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
            @Override
            protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
                Field field = (Field) this.member;
                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<>(1);
                    Assert.state(beanFactory != null, "No BeanFactory available");
                    TypeConverter typeConverter = beanFactory.getTypeConverter();
                    try {
                        //关键在此处,value怎么来的,其实一进去发现,依赖注入的根源,还是fac,那么直接往下走吧。
                        value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
                    }
                    catch (BeansException ex) {
                        throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
                    }
                    synchronized (this) {
                        if (!this.cached) {
                            if (value != null || this.required) {
                                this.cachedFieldValue = desc;
                                registerDependentBeans(beanName, autowiredBeanNames);
                                if (autowiredBeanNames.size() == 1) {
                                    String autowiredBeanName = autowiredBeanNames.iterator().next();
                                    if (beanFactory.containsBean(autowiredBeanName)) {
                                        if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                                            this.cachedFieldValue = new ShortcutDependencyDescriptor(
                                                    desc, autowiredBeanName, field.getType());
                                        }
                                    }
                                }
                            }
                            else {
                                this.cachedFieldValue = null;
                            }
                            this.cached = true;
                        }
                    }
                }
                if (value != null) {
                    ReflectionUtils.makeAccessible(field);
                    //通过反射将该值注入
                    field.set(bean, value);
                }
            }
    }
    

    beanFac是如何获取bean的呢?

    public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
            implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
        @Override
        @Nullable
        public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
                @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    
            descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
            if (Optional.class == descriptor.getDependencyType()) {
                return createOptionalDependency(descriptor, requestingBeanName);
            }
            else if (ObjectFactory.class == descriptor.getDependencyType() ||
                    ObjectProvider.class == descriptor.getDependencyType()) {
                return new DependencyObjectProvider(descriptor, requestingBeanName);
            }
            else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
                return new Jsr330ProviderFactory().createDependencyProvider(descriptor, requestingBeanName);
            }
            else {
                Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
                        descriptor, requestingBeanName);
                if (result == null) {
                    //最后定位到这个方法,直接往里边走
                    result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
                }
                return result;
            }
        }
    
        @Nullable
        public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
                @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    
            InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
            try {
                Object shortcut = descriptor.resolveShortcut(this);
                if (shortcut != null) {
                    return shortcut;
                }
    
                Class<?> type = descriptor.getDependencyType();
                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()));
                }
                Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
                if (multipleBeans != null) {
                    return multipleBeans;
                }
                //找到匹配的bean,那么看看如何找到呢
                Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
                if (matchingBeans.isEmpty()) {
                    if (isRequired(descriptor)) {
                        raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                    }
                    return null;
                }
    
                String autowiredBeanName;
                Object instanceCandidate;
    
                if (matchingBeans.size() > 1) {
                    autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
                    if (autowiredBeanName == null) {
                        if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
                            return descriptor.resolveNotUnique(type, matchingBeans);
                        }
                        else {
                            // In case of an optional Collection/Map, silently ignore a non-unique case:
                            // possibly it was meant to be an empty collection of multiple regular beans
                            // (before 4.3 in particular when we didn't even look for collection beans).
                            return null;
                        }
                    }
                    instanceCandidate = matchingBeans.get(autowiredBeanName);
                }
                else {
                    //刚刚好找到匹配的一个
                    // We have exactly one match.
                    Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
                    autowiredBeanName = entry.getKey();
                    instanceCandidate = entry.getValue();
                }
    
                if (autowiredBeanNames != null) {
                    autowiredBeanNames.add(autowiredBeanName);
                }
                if (instanceCandidate instanceof Class) {
                     //最后返回实例看最终的方法其实就是beanFactory.getBean(beanName);进入了获取实例的方法。
                    instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
                }
                Object result = instanceCandidate;
                if (result instanceof NullBean) {
                    if (isRequired(descriptor)) {
                        raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                    }
                    result = null;
                }
                if (!ClassUtils.isAssignableValue(type, result)) {
                    throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
                }
                return result;
            }
            finally {
                ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
            }
        }
    
        protected Map<String, Object> findAutowireCandidates(
                @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
            //其实此处就是根据类型找到候选者的名称,从bean的注册表中找到对应的子类
            String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                    this, requiredType, true, descriptor.isEager());
            Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
            //从已经解析过的依赖表中查询是否有缓存存在
            for (Class<?> autowiringType : this.resolvableDependencies.keySet()) {
                if (autowiringType.isAssignableFrom(requiredType)) {
                    Object autowiringValue = this.resolvableDependencies.get(autowiringType);
                    autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
                    if (requiredType.isInstance(autowiringValue)) {
                        result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
                        break;
                    }
                }
            }
            //从候选者中进行挑选
            for (String candidate : candidateNames) {
                //判断是不是依赖注入的候选者
                if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
                    //若是的话,则把候选者的信息加进去
                    addCandidateEntry(result, candidate, descriptor, requiredType);
                }
            }
            if (result.isEmpty() && !indicatesMultipleBeans(requiredType)) {
                // Consider fallback matches if the first pass failed to find anything...
                DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
                for (String candidate : candidateNames) {
                    if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor)) {
                        addCandidateEntry(result, candidate, descriptor, requiredType);
                    }
                }
                if (result.isEmpty()) {
                    // Consider self references as a final pass...
                    // but in the case of a dependency collection, not the very same bean itself.
                    for (String candidate : candidateNames) {
                        if (isSelfReference(beanName, candidate) &&
                                (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
                                isAutowireCandidate(candidate, fallbackDescriptor)) {
                            addCandidateEntry(result, candidate, descriptor, requiredType);
                        }
                    }
                }
            }
            //最后返回
            return result;
        }
    }
    

    简单总结一下,就是后置处理器会在bean实例化之后,去处理依赖注入,那么如何处理依赖注入呢,首先的话当然是生成依赖的元数据,随后未完善的实例会放入第三级缓存中,随后就是根据依赖元数据去找到对应的候选者,随后获取候选者的值,在获取候选者的实例的时候便会去创建候选者,只有当候选者完成实例化之后,才去将候选者的实例注入,若候选者依赖了该类型的bean,那么因为此前已经有三级缓存了,所以直接获取三级缓存就可以了,同时bean的缓存会提前暴露,到最后bean完成实例化,便直接到了一级缓存。依赖注入就解决了。

    相关文章

      网友评论

          本文标题:spring如何进行bean的实例化(二)依赖注入

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