Sping @Autowired依赖注入原理

发布于:2024-05-13 ⋅ 阅读:(114) ⋅ 点赞:(0)

Spring 依赖注入发生在bean的实例化之后初始化之前的阶段,可以查看:bean的创建过程

@Autowired

@Autowired由AutowiredAnnotationBeanPostProcessor实现依赖注入

寻找注入点:

  1. AutowiredAnnotationBeanPostProcessor实现了MergedBeanDefinitionPostProcessor接口
  2. 实现的MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition方法将会在bean实例化的时候被调用
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
    InjectionMetadata metadata = this.findAutowiringMetadata(beanName, beanType, (PropertyValues)null); //构造注入点,封装到metadata 中
    metadata.checkConfigMembers(beanDefinition);
}
  1. postProcessMergedBeanDefinition --> findAutowiringMetadata -->buildAutowiringMetadata
    buildAutowiringMetadata解析bean对象和其所有父类的属性和方法,判断是否包含Autowired注解,并构建InjectionMetadata 对象然后将其缓存
 private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
        if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {//判断bean的类型是否需要注入,如String类型,则不会进行依赖注入
            return InjectionMetadata.EMPTY;
        } else {
            List<InjectedElement> elements = new ArrayList();
            Class targetClass = clazz;

            do {
                List<InjectedElement> currElements = new ArrayList();
                ReflectionUtils.doWithLocalFields(targetClass, (field) -> { //遍历bean中的属性
                    MergedAnnotation<?> ann = this.findAutowiredAnnotation(field);//判断属性中是否有@Autowired、@Value、@Inject
                    if (ann != null) {
                        if (Modifier.isStatic(field.getModifiers())) {
                            if (this.logger.isInfoEnabled()) {
                                this.logger.info("Autowired annotation is not supported on static fields: " + field);
                            }

                            return;
                        }

                        boolean required = this.determineRequiredStatus(ann); //拿到@Autowired的required属性
                        currElements.add(new AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement(field, required));
                    }

                });
                ReflectionUtils.doWithLocalMethods(targetClass, (method) -> { //遍历bean中的方法
                    Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                    if (BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                        MergedAnnotation<?> ann = this.findAutowiredAnnotation(bridgedMethod);//判断方法中是否有@Autowired、@Value、@Inject
                        if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                            if (Modifier.isStatic(method.getModifiers())) {
                                if (this.logger.isInfoEnabled()) {
                                    this.logger.info("Autowired annotation is not supported on static methods: " + method);
                                }

                                return;
                            }

                            if (method.getParameterCount() == 0 && this.logger.isInfoEnabled()) {
                                this.logger.info("Autowired annotation should only be used on methods with parameters: " + method);
                            }

                            boolean required = this.determineRequiredStatus(ann); //拿到@Autowired的required属性 
                            PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                            currElements.add(new AutowiredAnnotationBeanPostProcessor.AutowiredMethodElement(method, required, pd));
                        }

                    }
                });
                elements.addAll(0, currElements);
                targetClass = targetClass.getSuperclass(); //通过循环遍历父类的属性和方法
            } while(targetClass != null && targetClass != Object.class);

            return InjectionMetadata.forElements(elements, clazz);
        }
    }
  1. ReflectionUtils.doWithLocalMethods遍历bean的所有属性,findAutowiredAnnotation遍历autowiredAnnotationTypes(@Autowired、@Value、@Inject),如果匹配到其中一个则返回,将其放入currElements集合
@Nullable
private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {
    MergedAnnotations annotations = MergedAnnotations.from(ao);
    Iterator var3 = this.autowiredAnnotationTypes.iterator();

    MergedAnnotation annotation;
    do {
        if (!var3.hasNext()) {
            return null;
        }

        Class<? extends Annotation> type = (Class)var3.next();
        annotation = annotations.get(type);
    } while(!annotation.isPresent());

    return annotation;
}

protected boolean determineRequiredStatus(MergedAnnotation<?> ann) {
    return this.determineRequiredStatus((AnnotationAttributes)ann.asMap((mergedAnnotation) -> {
        return new AnnotationAttributes(mergedAnnotation.getType());
    }, new Adapt[0]));
}
  1. autowiredAnnotationTypes在AutowiredAnnotationBeanPostProcessor实例化时被赋值
public AutowiredAnnotationBeanPostProcessor() {
        this.autowiredAnnotationTypes.add(Autowired.class);
        this.autowiredAnnotationTypes.add(Value.class);

        try {
            this.autowiredAnnotationTypes.add(ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
            this.logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
        } catch (ClassNotFoundException var2) {
        }

    }
  1. ReflectionUtils.doWithLocalMethods遍历bean的所有方法,进行和属性类似的逻辑

进行依赖注入:

  1. AutowiredAnnotationBeanPostProcessor实现了SmartInstantiationAwareBeanPostProcessor接口
  2. 实现的SmartInstantiationAwareBeanPostProcessor.postProcessProperties方法将会在bean进行依赖注入的时候被调用
  3. 从缓存中拿到metadata
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    InjectionMetadata metadata = this.findAutowiringMetadata(beanName, bean.getClass(), pvs); //从缓存中拿到metadata 

    try {
        metadata.inject(bean, beanName, pvs);
        return pvs;
    } catch (BeanCreationException var6) {
        throw var6;
    } catch (Throwable var7) {
        throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", var7);
    }
}
  1. 然后调用AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement.inject对属性进行依赖注入,在resolveFieldValue方法获取值后,通过反射进行赋值
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    Field field = (Field)this.member;
    Object value;
    if (this.cached) {
        try {
            value = AutowiredAnnotationBeanPostProcessor.this.resolvedCachedArgument(beanName, this.cachedFieldValue);//获取需要进行注入的bean对象
        } catch (NoSuchBeanDefinitionException var7) {
            value = this.resolveFieldValue(field, bean, beanName);
        }
    } else {
        value = this.resolveFieldValue(field, bean, beanName);
    }

    if (value != null) {
        ReflectionUtils.makeAccessible(field);//通过反射对bean赋值
        field.set(bean, value);
    }

}
  1. 调用resolveFieldValue方法,根据filed从BeanFactory中查到对应的Bean对象。
@Nullable
private Object resolveFieldValue(Field field, Object bean, @Nullable String beanName) {
    DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
    desc.setContainingClass(bean.getClass());
    Set<String> autowiredBeanNames = new LinkedHashSet(1);
    Assert.state(AutowiredAnnotationBeanPostProcessor.this.beanFactory != null, "No BeanFactory available");
    TypeConverter typeConverter = AutowiredAnnotationBeanPostProcessor.this.beanFactory.getTypeConverter();

    Object value;
    try {
        value = AutowiredAnnotationBeanPostProcessor.this.beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
    } catch (BeansException var12) {
        throw new UnsatisfiedDependencyException((String)null, beanName, new InjectionPoint(field), var12);
    }

    synchronized(this) {
        if (!this.cached) {
            Object cachedFieldValue = null;
            if (value != null || this.required) {
                cachedFieldValue = desc;
                AutowiredAnnotationBeanPostProcessor.this.registerDependentBeans(beanName, autowiredBeanNames);
                if (autowiredBeanNames.size() == 1) {
                    String autowiredBeanName = (String)autowiredBeanNames.iterator().next();
                    if (AutowiredAnnotationBeanPostProcessor.this.beanFactory.containsBean(autowiredBeanName) && AutowiredAnnotationBeanPostProcessor.this.beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                        cachedFieldValue = new AutowiredAnnotationBeanPostProcessor.ShortcutDependencyDescriptor(desc, autowiredBeanName, field.getType());
                    }
                }
            }

            this.cachedFieldValue = cachedFieldValue;
            this.cached = true;
        }

        return value;
    }
}
  1. 同第4步,调用进行AutowiredAnnotationBeanPostProcessor.AutowiredMethodElement.inject对属性进行依赖注入,在resolveMethodArguments方法获取值后,通过反射进行赋值

    protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        if (!this.checkPropertySkipping(pvs)) {
            Method method = (Method)this.member;
            Object[] arguments;
            if (this.cached) {
                try {
                    arguments = this.resolveCachedArguments(beanName);
                } catch (NoSuchBeanDefinitionException var8) {
                    arguments = this.resolveMethodArguments(method, bean, beanName);
                }
            } else {
                arguments = this.resolveMethodArguments(method, bean, beanName);
            }
    
            if (arguments != null) {
                try {
                    ReflectionUtils.makeAccessible(method);
                    method.invoke(bean, arguments);//反射调用方法进行依赖注入
                } catch (InvocationTargetException var7) {
                    throw var7.getTargetException();
                }
            }
    
        }
    }
    
  2. 同第5步,调用resolveMethodArguments方法,根据method从BeanFactory中查到对应的Bean对象。

@Nullable
        private Object[] resolveMethodArguments(Method method, Object bean, @Nullable String beanName) {
            int argumentCount = method.getParameterCount();
            Object[] arguments = new Object[argumentCount];
            DependencyDescriptor[] descriptors = new DependencyDescriptor[argumentCount];
            Set<String> autowiredBeans = new LinkedHashSet(argumentCount);
            Assert.state(AutowiredAnnotationBeanPostProcessor.this.beanFactory != null, "No BeanFactory available");
            TypeConverter typeConverter = AutowiredAnnotationBeanPostProcessor.this.beanFactory.getTypeConverter();

            for(int ix = 0; ix < arguments.length; ++ix) {
                MethodParameter methodParam = new MethodParameter(method, ix);
                DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
                currDesc.setContainingClass(bean.getClass());
                descriptors[ix] = currDesc;

                try {
                    Object arg = AutowiredAnnotationBeanPostProcessor.this.beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
                    if (arg == null && !this.required) {
                        arguments = null;
                        break;
                    }

                    arguments[ix] = arg;
                } catch (BeansException var17) {
                    throw new UnsatisfiedDependencyException((String)null, beanName, new InjectionPoint(methodParam), var17);
                }
            }

            synchronized(this) {
                if (!this.cached) {
                    if (arguments == null) {
                        this.cachedMethodArguments = null;
                    } else {
                        DependencyDescriptor[] cachedMethodArguments = (DependencyDescriptor[])Arrays.copyOf(descriptors, arguments.length);
                        AutowiredAnnotationBeanPostProcessor.this.registerDependentBeans(beanName, autowiredBeans);
                        if (autowiredBeans.size() == argumentCount) {
                            Iterator<String> it = autowiredBeans.iterator();
                            Class<?>[] paramTypes = method.getParameterTypes();

                            for(int i = 0; i < paramTypes.length; ++i) {
                                String autowiredBeanName = (String)it.next();
                                if (AutowiredAnnotationBeanPostProcessor.this.beanFactory.containsBean(autowiredBeanName) && AutowiredAnnotationBeanPostProcessor.this.beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
                                    cachedMethodArguments[i] = new AutowiredAnnotationBeanPostProcessor.ShortcutDependencyDescriptor(descriptors[i], autowiredBeanName, paramTypes[i]);
                                }
                            }
                        }

                        this.cachedMethodArguments = cachedMethodArguments;
                    }

                    this.cached = true;
                }

                return arguments;
            }
        }

网站公告

今日签到

点亮在社区的每一天
去签到