天天看點

spring依賴注入——注解注入

之前分析spring的依賴注入時,主要分析的是xml配置方式。但是在實際項目中,我們其實用的更多的是注解方式。這一篇部落格會分析下spring是如何處理這種注解注入的。(主要分析最常使用的@Autowired 和 @Resource注解)

注解注入的開啟 annotation-config

SpringBoot方式暫且不管,正常來說我們要想啟用注解注入都需要有這樣一個配置:

<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation=" http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
       http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  
    <context:annotation-config/>  
  
</beans> 
           

那麼我們就從annotation-config的解析開始

spring依賴注入——注解注入

從代碼很容易看出,annotation-config的解析是在org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser類裡。

PostProcessor的注冊

對于annotation-config的處理,依然隻關心最核心的部分。跟着源碼走,發現一部分非常核心的邏輯是在AnnotationConfigUtils裡。在處理annotation-config時候,spring配置了各種PostProcessor類

ConfigurationClassPostProcessor

AutowiredAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor

....

spring依賴注入——注解注入

populateBean

我們在分析populateBean時候,隻是曾跳過一段關于關于PostProcessor的回調方法。而Spring正是通過PostProcessor來實作注解方式的依賴注入的。

同樣,這裡把PostProcessor這一段單獨貼出來

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    PropertyValues pvs = mbd.getPropertyValues();

    if (bw == null) {
        if (!pvs.isEmpty()) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            // Skip property population phase for null instance.
            return;
        }
    }

    // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    // state of the bean before properties are set. This can be used, for example,
    // to support styles of field injection.
    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;
    }

    //... 省略AutowiredMode等

    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    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) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvs == null) {
                        return;
                    }
                }
            }
        }
        if (needsDepCheck) {
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }

    applyPropertyValues(beanName, mbd, bw, pvs);
}
           

@Autowired處理 AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues

從annotatation-config的處理我們知道了,spring其實配置了很多的PostProcessor。這裡我隻分析我們最常用的一個

AutowiredAnnotationBeanPostProcessor

這個類對@Autowired注解進行了處理

AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues

随後我們就來看看,究竟這個AutowiredAnnotationBeanPostProcessor是如何對這些依賴注入使用的注解進行處理的

public PropertyValues postProcessPropertyValues(
        PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

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

這裡的代碼很簡單,找到InjectionMetadata

調用InjectionMetadata進行注入

那麼我們就要先弄清楚,這個InjectionMetadata究竟是什麼?

Internal class for managing injection metadata.

Not intended for direct use in applications.

注釋裡說是一個用于管理

注入的中繼資料

的管理類,到這裡我們還是不清楚它是幹啥用的。

是以繼續深入分析InjectionMetadata是如何建構的。findAutowiringMetadata這個方法大概就是,如果有的話,就從緩存擷取,如果沒有的話,就build一個。是以我們直接看build的邏輯就好了

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
    Class<?> targetClass = clazz;

    do {
        final LinkedList<InjectionMetadata.InjectedElement> currElements =
                new LinkedList<>();

        //找到所有的标注了 @Autowired @Value 等注解的field,封裝成一個AutowiredFieldElement 添加到currElements裡
        ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                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));
                }
            }
        });

        //找到所有的标注了 @Autowired @Value 等注解的method,封裝成一個AutowiredFieldElement 添加到currElements裡
        ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                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 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);
    
    //封裝找到了的method和field,放到InjectionMetadata
    return new InjectionMetadata(clazz, elements);
}
           

這裡的邏輯也很簡單

1)找到所要注入的類,标記有 @Autowired @Value等注解的 field和method 添加到一個list中

2)以list和這個class封裝成一個InjectionMetadata

3)注意這裡的

while (targetClass != null && targetClass != Object.class);

除了掃描自己類的@Autowired等注解,還會掃描父類的注解,這也解釋了,為什麼繼承了抽象類的時候,可以同時繼承其 @Autowired等注解

下面的例子簡單說明了父類注入的場景

抽象類的注入

@Component
public class BaseDao {

    //各種資料庫操作方式...
}
           
//抽象類,隻是注入了dao
public abstract class BaseService {

    @Autowired
    protected BaseDao dao;

    public BaseDao getDao() {
        return dao;
    }

    public void setDao(BaseDao dao) {
        this.dao = dao;
    }
}
           

StudentService 繼承了BaseService,這樣就可以直接在自己的方法裡使用dao

public class StudentService extends BaseService {
}
           

xml配置,xml隻需要配置Service和dao,就會自動将dao注入到StudentService中

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--<context:component-scan base-package="com.hdj.learn.spring.annotation"/>-->

    <bean id="dao" class="com.hdj.learn.spring.annotation.abs.BaseDao">
    </bean>

    <bean id="studentService" class="com.hdj.learn.spring.annotation.abs.StudentService"/>

    <context:annotation-config/>
</beans>
           

@Autowired的繼承正是通過上文分析的,一個簡單的do while就實作了。

回到 InjectionMetadata

經過上文的分析,我們就大概知道了所謂的InjectionMetadata究竟是個什麼。它存儲了某個類,以及這個類裡需要被依賴注入的element(标注了@Autowired,@Value等注解的方法或者成員變量)

分析到這裡後,随後的就是InjectionMetadata.inject方法。

大概就是周遊之前的List<InjectedElement> 然後調用 InjectedElement.inject方法

protected void inject(Object bean, String beanName, 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);
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            //找到要注入的值
            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);
    }
}
           

特别熟悉的代碼,大體和之前通過xml依賴注入的代碼一樣。找到要注入的對象,注入進去。

總結

這篇部落格分析了spring對于注解标記的變量,是如何進行注入了。主要分析了我們最常用的 @Autowired 、@Value 注解。依賴注入分析到這裡,基本上就能大緻了解spring依賴注入的步驟。當然還是有種無法統一的感覺,下一篇部落格會試着從上層到下分析spring依賴注入究竟是如何設計的,以及從spring的依賴注入中我們能學到什麼。