@Import底層實現原理
日常專案中,使用註解@EnableAspectJAutoProxy@EnableAsync
這裡面涉及對@Import註解支撐的底層原理:ConfigurationClassPostProcessor 這個類,說到這個類,我們要先從SpringBoot啟動流程說起。
首先,看springboot啟動流程中的一步:
SpringApplication物件的run方法,建立上下文context = createApplicationContext(); 這一步,會建立AnnotationConfigServletWebServerApplicationContext物件:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
(ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
類圖關係如下:
AnnotationConfigServletWebServerApplicationContext類有兩個重要的屬性:private final AnnotatedBeanDefinitionReader reader;private final ClassPathBeanDefinitionScanner scanner;
建立AnnotationConfigServletWebServerApplicationContext物件時, 呼叫構造方法,會初始化該物件的上面兩個屬性。
見:
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
在new AnnotatedBeanDefinitionReader(this)物件時,裡面會涉及AnnotatedBeanDefinitionReader建構函式
AnnotatedBeanDefinitionReader建構函式AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);