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

前言

  開心一刻html

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

前情回顧

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

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

@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-BeanPostProcessorspringboot

  AnimalConfigapp

View Code

  AnimalServiceImplide

@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

  AnimalTestspring-boot

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

    @Autowired
    private IAnimalService animalService;

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

  運行結果post

  咱們在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也差不太多,就不演示了,都是經過反射實現的 。

總結

  一、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

  二、自動裝配與自動配置

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

  三、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是如何工做的

相關文章
相關標籤/搜索