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查看。
未完,待续