参考链接1
参考链接2
所参照代码为Springboot2.1.1
默认情况下,扫描范围是主类xxxApplication所在包及其子目录,可以在后面的具体实现中看到。
从主类中的SpringApplication.run(xxxApplication.class, args);一直点击进入run方法的实现,这里可以看到run方法里有几个关于context的方法分别是:
createApplicationContext()
prepareContext(xxx,xx)
refreshContext(context)
public ConfigurableApplicationContext run(String... args) {
...
try {
...
context = createApplicationContext();
...
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
....
catch (Throwable ex) {
}
逐个分析:
1.createApplicationContext()
这个方法返回一个类型为AnnotationConfigServletWebServerApplicationContext的context,可以点进去看到这个class为AnnotationConfigServletWebServerApplicationContext类型。
protected ConfigurableApplicationContext createApplicationContext() {
...
case SERVLET:
contextClass = Class.forName(**DEFAULT_SERVLET_WEB_CONTEXT_CLASS**);
break;
case ...
}
}
....
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
该类的一个父类GenericApplicationContext中,创建了一个beanFactory,这个beanFactory实现了BeanDefinitionRegistry的接口,后面会用到。
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
createApplicationContext返回的语句中调用了AnnotationConfigServletWebServerApplicationContext类的构造函数,
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
进入构造函数中的第一个AnnotatedBeanDefinitionReader,一直点到registerAnnotationConfigProcessors的方法:
public static Set registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
//创建了一个beanFactory
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
.....
}
Set beanDefs = new LinkedHashSet<>(8);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
//添加了一个类型为CON