@Configuration底層原理

 
AnnotationConfigApplicationContext act = new 
                                     AnnotationConfigApplicationContext(MyConfigure.class);
 Student stduent = (Student) act.getBean(Student.class);
 studnt.say();

進入 AnnotationConfigApplicationContext 的構造方法中

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		this();
		register(annotatedClasses);
		refresh();
	}

  其中  this() 方法調用了無參構造方法,由於 AnnotationConfigApplicationContext 繼承 GenericApplicationContext ,

GenericApplicationContext  包含成員 變量  beanFactory (私有,但是子類可以通過 getBeanFactory()方法訪問 )

 

那麼問題來了,@ComponentScan標註的對象何時加入 beanDefinitionMap  中的呢?

其實很簡單,我們可以通過 debug 模式,查看 beanDefinitionMap 的size大小

 

通過上圖可以看到,在執行到 register()方法時,只有默認的6個(AnnotatedBeanDefinitionReader時spring默認創建的)。

此時  MyConfigure 類也沒生成 beanDefinition ,猜測  register(annotatedClasses) 方法會將 MyConfigure生成 beanDefinition,F8執行,發現猜測時正確的。

 

通過此方法,我們就能看到,@ComponentScan標註的對象何時加入 beanDefinitionMap  中的,由於篇幅問題,就不再貼圖了,直接上步驟。大家可以自己照這個方式進行debug查看。

 

 

未完,待續

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章