Spring框架的AnnotationConfigApplicationContext初始化流程(1)

31 阅读1分钟

配置类

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@ComponentScan("org.springframework.dtx")
@EnableAspectJAutoProxy
public class Config {
}

测试示例

public class Main {
    public static void main(String[] args) {

       AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

}

AnnotationConfigApplicationContext的构造方法

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

先看看this方法

public AnnotationConfigApplicationContext() {
    StartupStep createAnnotatedBeanDefReader = getApplicationStartup().start("spring.context.annotated-bean-reader.create");
    this.reader = new AnnotatedBeanDefinitionReader(this);
    createAnnotatedBeanDefReader.end();
    this.scanner = new ClassPathBeanDefinitionScanner(this);
}

职责是初始化AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner (AnnotationConfigApplicationContext的成员变量)

public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {

    private final AnnotatedBeanDefinitionReader reader;

    private final ClassPathBeanDefinitionScanner scanner;
    
    ..........
}

因为AnnotationConfigApplicationContext继承的父类GenericApplicationContext的无参构造方法会初始化一个beanFactory

public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {

    private final DefaultListableBeanFactory beanFactory;

    .......
    
    public GenericApplicationContext() {
       this.beanFactory = new DefaultListableBeanFactory();
    }
    .......
   }