1. 程式人生 > >spring的自動裝配,騷話@Autowired的底層工作原理

spring的自動裝配,騷話@Autowired的底層工作原理

前言

  開心一刻

    十年前,我:我交女票了,比我大兩歲。媽:不行!趕緊分!
    八年前,我:我交女票了,比我小兩歲,外地的。媽:你就不能讓我省點心?
    五年前,我:我交女票了,市長的女兒。媽:別人還能看上你?分了吧!
    今年,我挺著大肚子踏進家門。媽:閨女啊,你終於開竅了 !

前情回顧

  Spring拓展介面之BeanPostProcessor,我們來看看它的底層實現中講到了spring對BeanPostProcessor的底層支援,並且知道了BeanPostProcessor的兩個方法:postProcessBeforeInitialization、postProcessAfterInitialization的執行時機,沒看的小夥伴可以回過頭去看看。本來spring的自動裝配是打算放到上一篇博文中詳細講解的,可後來覺得篇幅可能太大了(細心的小夥伴可能會有這樣的表情:,除了幾幅圖,真沒什麼內容!),既然你們都感覺出來了,那我也就明人不說暗話了,之所以沒放到上篇講解,確實是因為篇幅太大了(哈哈哈,是不是很想打我? ); 好了,我們言歸正傳,之所以沒放到上篇來講,篇幅只是原因之一,最主要的原因是發現我犯錯了! 犯什麼錯了呢(不是黃賭毒啊,那是犯罪,我是正人君子!),我想當然了! 理所當然的認為自動裝配是在AutowiredAnnotationBeanPostProcessor的postProcessBeforeInitialization或postProcessAfterInitialization中實現的,我們來看下AutowiredAnnotationBeanPostProcessor類繼承圖

  它間接實現了BeanPostProcessor,我們再去看下那兩個方法(在父類InstantiationAwareBeanPostProcessorAdapter中)

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return bean;
}
View Code

  竟然啥也沒幹,只是簡單的return bean; 當自己深以為然的認知被推翻時,那感覺真是斃了狗了 所以自動裝配不能和BeanPostProcessor放一塊講,不得不開兩篇來分開講,我們都知道:強扭的瓜不甜!

自動裝配簡單示例

  我們先來看一個簡單的自動裝配的示例,完整例項程式碼:spring-boot-BeanPostProcessor

  AnimalConfig

View Code

  AnimalServiceImpl

@Service
public class AnimalServiceImpl implements IAnimalService {

    @Autowired
    private Dog dog;
    @Resource
    private Cat cat;
    @Inject
    private Pig pig;

    @Override
    public void printName() {
        System.out.println(dog.getName());
        System.out.println(cat.getName());
        System.out.println(pig.getName());
    }
}
View Code

  AnimalTest

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
public class AnimalTest {

    @Autowired
    private IAnimalService animalService;

    @Test
    public void test() {
        animalService.printName();
    }
}
View Code

  執行結果

  我們在AnimalConfig中只是將Dog、Cat、Pig的例項註冊到了spring容器,那為什麼AnimalServiceImpl例項能夠直接應用這些例項了,我們並沒有手動的將這些例項賦值到AnimalServiceImpl例項呀? 這其實就是spring提供的自動裝配功能,雖然我們沒有手動的將這些例項賦值到AnimalServiceImpl例項,但是我們發現AnimalServiceImpl的屬性例項上多了一些註解:@Autowired、@Resource、@Inject,spring通過這些註解自動完成了屬性例項的注入,而不需要我們手動的去賦值了;那麼spring是如何實現自動裝配的呢? 我們慢慢往下看(注意:後文主要以@Autowired為例來講解)

自動裝配原始碼解析

  AutowiredAnnotationBeanPostProcessor的例項化與註冊

    不管怎麼說,AutowiredAnnotationBeanPostProcessor終歸還是一個BeanPostProcessor,那麼它的例項化與註冊(註冊到spring的beanFactory)過程與BeanPostProcessor的例項化與註冊一樣,在spring的啟動過程中,重新整理上下文(refresh)的時候,會呼叫registerBeanPostProcessors(beanFactory)方法完成BeanPostProcessor的例項化與註冊,後續再呼叫finishBeanFactoryInitialization(beanFactory)例項化非延遲載入的單例bean時,會用到上述註冊的BeanPostProcessor

    AutowiredAnnotationBeanPostProcessor的構造方法值得我們看看

public AutowiredAnnotationBeanPostProcessor() {
    this.autowiredAnnotationTypes.add(Autowired.class);
    this.autowiredAnnotationTypes.add(Value.class);
    try {
        this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
        logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
    }
    catch (ClassNotFoundException ex) {
        // JSR-330 API not available - simply skip.
    }
}
View Code

    預設情況下,AutowiredAnnotationBeanPostProcessor支援@Autowired和@Value,如果類路徑下有java.inject.Inject(也就是引入了javax.inject.jar),那麼也支援@Inject註解,是不是與我們最初的認知有些不一樣?。將支援的註解放到了autowiredAnnotationTypes屬性中,後續會用到該屬性

  bean的例項化與依賴注入

    預設情況下,spring會把spring容器中的bean當成non-lazy-init singleton來處理(有些特殊的bean除外),也就是說會在spring的啟動過程中就會逐個例項化這些bean,並對這些bean進行依賴注入;當我們真正用到這些bean的時候,直接用就行,不用再去例項化,也不用再去注入bean的相關依賴,spring是不是很厲害?。具體是不是說的這樣,大家準備好花生、瓜子和啤酒,好戲即將開始

    我們先找到正確的入口,然後用下圖省略掉無聊的前戲,直接進入高潮:doCreateBean(不應該是這個嗎,一天天的盡胡思亂想)

    doCreateBean內容如下

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
        throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 建立bean例項
        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.
    // 允許後置處理器來修改bean定義
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                // 呼叫MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法
                // AutowiredAnnotationBeanPostProcessor實現了MergedBeanDefinitionPostProcessor,即MergedBeanDefinitionPostProcessor的MergedBeanDefinitionPostProcessor會被呼叫
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // Eagerly cache singletons to be able to resolve circular references 立即快取單例以便能夠解析迴圈引用
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    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");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // 填充bean,包含依賴注入
        populateBean(beanName, mbd, instanceWrapper);
        // 初始化bean,BeanPostProcessor的兩個方法在此中被呼叫
        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) {
        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;
}
View Code

    我們重點看下posProcessMergedBeanDefinition方法和populateBean方法

  posProcessMergedBeanDefinition

    可以看到會讀取bean的field和method上的註解,並判斷該註解是否在autowiredAnnotationTypes中,如果在則將field封裝成AutowiredFiledElement物件、將method封裝成AutoWiredMethodElement物件,並存放到InjectionMetadata物件的Set<InjectedElement> checkedElements屬性中,最後將該InjectionMetadata物件快取到了AutowiredAnnotationBeanPostProcessor的Map<String, InjectionMetadata> injectionMetadataCache屬性中;說白了就是將bean中被@Autowried(當然還包括@Value、@Inject)修飾的field、method找出來,封裝成InjectionMetadata物件並快取起來,就這麼簡單。不僅僅是上圖中的animalServiceImpl這一個bean,spring中所有的非延遲載入的bean都會走這個建立流程。是不是很簡單,是不是幹勁十足了

  populateBean

    呼叫AutowiredAnnotationBeanPostProcessor的postProcessPropertyValues方法,從injectionMetadataCache中獲取當前bean的依賴資訊,比如animalServiceImpl依賴的dog、pig(有人可能會有這樣的疑問:cat呢? cat是被@Resource修飾的,而@Resource不是由AutowiredAnnotationBeanPostProcessor支援,後續會講由誰支援),然後逐個將依賴bean注入到目標bean(將dog、pig例項注入到animalServiceImpl例項中);依賴bean從哪來呢?還是從beanFactory中獲取,如果不存在,則又回到bean的建立過程把依賴bean(dog、pig)創建出來,流程與建立animalServiceImpl例項一模一樣,也就說在animalServiceImpl例項的依賴注入過程中會把dog、pig物件也創建出來,而不是等到spring逐個例項化bean的過程中輪到dog、pig才例項化dog、pig,那後續輪到dog、pig時怎麼辦了,spring會把建立的bean快取起來,下次就直接從快取中取了。上圖只演示Field的,Method也差不太多,就不演示了,都是通過反射實現的 。

總結

  1、bean的建立與初始化

    (1)instanceWrapper = createBeanInstance(beanName, mbd, args)  建立目標bean例項;

    (2)applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)  尋找目標bean的依賴;

    (3)populateBean(beanName, mbd, instanceWrapper)  填充目標bean,完成依賴注入; (這裡的迴圈依賴,有興趣的可以自行去琢磨下)

    (4)initializeBean(beanName, exposedObject, mbd)  初始化目標bean

  2、自動裝配與自動配置

    自動配置一般而言說的是spring的@Autowired,是spring的特性之一,而自動配置是springboot的@Configuration,是springboot的特性之一

  3、Spring支援幾下幾種自動裝配的註解

    @Autowired、@Inject、@Resource以及@Value,用的最多的應該是@Autowired(至少我是這樣的),@Inject和@Value也是由AutowiredAnnotationBeanPostProcessor支援,而@Resource是由CommonAnnotationBeanPostProcessor支援(還支援@PostConstruct、@PreDestroy等註解)

    關於@Value與@Autowired,不知道大家是否清楚他們之間的區別,不清楚的可以看看:Spring: @Value vs. @Autowired或者spring的官方文件,總結下:@Value >= @Autowired,只是平時應用中,@Value更多的是用來注入配置值(如:@Value("${db.url}")),而@Autowired則是bean物件的注入

參考

  JAVA 註解的基本原理

  深入理解Spring系列之十四:@Autowired是如何工作的