一、示例代码
@ComponentScan("org.springframework.examples")
public class AnnotationConfigApplicationContextTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AnnotationConfigApplicationContextTest.class);
}
}
此处创建了注解配置的ApplicationContext,执行main函数,我们进入到其构造器去看:
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given component classes and automatically refreshing the context.
* @param componentClasses one or more component classes — for example,
* {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
// 调用无参、构造器
this();
// 注册我们传进来的配置类
register(componentClasses);
// 容器刷新启动
refresh();
}
/**
* 无参构造器
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
*/
public AnnotationConfigApplicationContext() {
// 注注册 BeanDefinition 读取器 主要是Spring内置的一些BeanFactoryPostProcessor
this.reader = new AnnotatedBeanDefinitionReader(this);
// 这里的scanner 主要是用作程序员手动调用 scanner放发
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
二、前情提要
AnnotationConfigApplicationContext
无参构造器中实例化了AnnotatedBeanDefinitionReader
。
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.