protected ConfigurableApplicationContext createApplicationContext() { return this.applicationContextFactory.create(this.webApplicationType); //上下文工厂根据应用程序类型创建应用程序上下文 .create方法可拓展,但是框架方法中没有实现 -> }
//webApplicationType:
this.webApplicationType = WebApplicationType.deduceFromClasspath();//根据路径推断应用程序类型 返回程序类型
static WebApplicationType deduceFromClasspath() { if (ClassUtils.isPresent("org.springframework.web.reactive.DispatcherHandler", (ClassLoader)null) && !ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", (ClassLoader)null) && !ClassUtils.isPresent("org.glassfish.jersey.servlet.ServletContainer", (ClassLoader)null)) { return REACTIVE; } else { String[] var0 = SERVLET_INDICATOR_CLASSES; int var1 = var0.length; for(int var2 = 0; var2 < var1; ++var2) { String className = var0[var2]; if (!ClassUtils.isPresent(className, (ClassLoader)null)) { return NONE; } } return SERVLET; } }
//applicationContextFactory
ApplicationContextFactory DEFAULT = (webApplicationType) -> { try { switch(webApplicationType) { case SERVLET: return new AnnotationConfigServletWebServerApplicationContext(); case REACTIVE: return new AnnotationConfigReactiveWebServerApplicationContext(); default: return new AnnotationConfigApplicationContext(); //注释配置上下文-> todo } } catch (Exception var2) { throw new IllegalStateException("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2); } };
public AnnotationConfigApplicationContext() { StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create"); //启动执行bean-reader创建 this.reader = new AnnotatedBeanDefinitionReader(this); //注释读取器 读取bean,设置Bean定义-> createAnnotatedBeanDefReader.end(); //执行结束 this.scanner = new ClassPathBeanDefinitionScanner(this); //新建实例:注释扫描器-> }
AnnotatedBeanDefinitionReader属性:
BeanDefinitionRegistry registry; //bean定义注册: AnnotationConfigApplicationContext -> BeanNameGenerator beanNameGenerator; //bean名字生成器 -> ScopeMetadataResolver scopeMetadataResolver; //范围解析器 -> ConditionEvaluator conditionEvaluator; //条件评估 ->
//创建AnnotatedBeanDefinitionReader public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) { this(registry, getOrCreateEnvironment(registry)); // registey: AnnotationConfigApplicationContext.class -> }
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) { this.beanNameGenerator = AnnotationBeanNameGenerator.INSTANCE; //bean名字生成 -> this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(); //范围解析-> Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); Assert.notNull(environment, "Environment must not be null"); this.registry = registry; this.conditionEvaluator = new ConditionEvaluator(registry, environment, (ResourceLoader)null); //信息配置-> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); //注册处理器 对Bean注册Bean定义-> }
//beanNameGenerator创建:
public static final AnnotationBeanNameGenerator INSTANCE = new AnnotationBeanNameGenerator(); //获得一个类实例 属性:Map<String, Set<String>> metaAnnotationTypesCache
//scopeMetadataResolver创建:
public AnnotationScopeMetadataResolver() { this.defaultProxyMode = ScopedProxyMode.NO; }
//conditionEvaluator创建
private final ConditionEvaluator.ConditionContextImpl context; public ConditionEvaluator(@Nullable BeanDefinitionRegistry registry, @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) { this.context = new ConditionEvaluator.ConditionContextImpl(registry, environment, resourceLoader);//实例
}
public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry, @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) { this.registry = registry; this.beanFactory = this.deduceBeanFactory(registry); //获取BeanFactory, registry: AnnotationConfigApplicationContext -> this.environment = environment != null ? environment : this.deduceEnvironment(registry); //获取环境 this.resourceLoader = resourceLoader != null ? resourceLoader : this.deduceResourceLoader(registry); //资源加载器,存在Map<Class<?>, Map<Resource, ?>> resourceCaches this.classLoader = this.deduceClassLoader(resourceLoader, this.beanFactory);//有beanFactory的话,从beanFactory中获取类加载器,否则,使用默认类加载器 }
private ConfigurableListableBeanFactory deduceBeanFactory(@Nullable BeanDefinitionRegistry source) { //source: AnnotationConfigApplicationContext if (source instanceof ConfigurableListableBeanFactory) { return (ConfigurableListableBeanFactory)source; } else { return source instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext)source).getBeanFactory() : null; //-> } }
//AbstractApplicationContext.getBeanFactory
public final ConfigurableListableBeanFactory getBeanFactory() { return this.beanFactory; //类型:DefaultListableBeanFactory 初始化 -> }
public DefaultListableBeanFactory() { this.autowireCandidateResolver = SimpleAutowireCandidateResolver.INSTANCE;//解析器 this.resolvableDependencies = new ConcurrentHashMap(16);//可解析的依赖? todo this.beanDefinitionMap = new ConcurrentHashMap(256); //bean定义 this.mergedBeanDefinitionHolders = new ConcurrentHashMap(256); //bean定义容器? todo this.allBeanNamesByType = new ConcurrentHashMap(64);//按类型获取beanName? todo this.singletonBeanNamesByType = new ConcurrentHashMap(64);//按类型获取单例beanName? todo this.beanDefinitionNames = new ArrayList(256);//bean定义的名字 this.manualSingletonNames = new LinkedHashSet(16);//手动单例名字 bean定义过程中用到 }
//registerAnnotationConfigProcessors public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) { registerAnnotationConfigProcessors(registry, (Object)null); -> todo }
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) { DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); //默认方式获取beanFactory
if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); //设置dependencyComparator为AnnotationAwareOrderComparator
} if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); //设置AutowireCandidateResolver自动配置解析器为基于注解的解析器 } }
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet(8); //bean定义 beanDefinition-beanName beanDefinition定义Bean类型:单例或原型 角色:application/support/infrastructure RootBeanDefinition def; //根beanDefinition if (!registry.containsBeanDefinition("org.springframework.context.annotation.internalConfigurationAnnotationProcessor")) { //检查beanFactory中的beanDefinitionMap是否有这项 def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); //若没有,新建,beanclass设为ConfigurationClassPostProcessor def.setSource(source); //为根bean定义设置资源 默认为null beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"));//注册bean -> ,添加到beanDefinitionHolder集合中 }
//依次创建beanDefinition if (!registry.containsBeanDefinition("org.springframework.context.annotation.internalAutowiredAnnotationProcessor")) { def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalAutowiredAnnotationProcessor")); }
if (jsr250Present && !registry.containsBeanDefinition("org.springframework.context.annotation.internalCommonAnnotationProcessor")) { def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalCommonAnnotationProcessor")); }
if (jpaPresent && !registry.containsBeanDefinition("org.springframework.context.annotation.internalPersistenceAnnotationProcessor")) { def = new RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor", AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException var6) { throw new IllegalStateException("Cannot load optional framework class: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor", var6); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalPersistenceAnnotationProcessor")); }
if (!registry.containsBeanDefinition("org.springframework.context.event.internalEventListenerProcessor")) { def = new RootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.event.internalEventListenerProcessor")); }
if (!registry.containsBeanDefinition("org.springframework.context.event.internalEventListenerFactory")) { def = new RootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.event.internalEventListenerFactory")); }
return beanDefs; //返回创建好的beanDefinition集合 }
//注册处理器 private static BeanDefinitionHolder registerPostProcessor(BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) { definition.setRole(2); //设置角色 registry.registerBeanDefinition(beanName, definition);//注册bean定义,有继承的方法,获取继承的方法 ,添加入beanDefinitionMap中,beanName添加进beanDefinitionNames中,从ManualSingletonName中移除beanName return new BeanDefinitionHolder(definition, beanName); }
//Scanner public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) { this(registry, true); -> }
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) { this(registry, useDefaultFilters, getOrCreateEnvironment(registry)); -> }
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) { this(registry//AnnotationConfigApplicationContext, useDefaultFilters // true, environment//AnnotationConfigApplicationContext, registry instanceof ResourceLoader ? (ResourceLoader)registry : null); -> }
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment, @Nullable ResourceLoader resourceLoader) { this.beanDefinitionDefaults = new BeanDefinitionDefaults(); //默认bean定义 this.beanNameGenerator = AnnotationBeanNameGenerator.INSTANCE; //默认beanNameGenerator this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(); //默认区域解析器 this.includeAnnotationConfig = true; Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); this.registry = registry; if (useDefaultFilters) { this.registerDefaultFilters(); } this.setEnvironment(environment); this.setResourceLoader(resourceLoader); }