详细跟踪spring容器的启动过程
org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(java.lang.Class<?>...)
//初始化AnnotationConfigApplicationContext,主要就是初始化AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext()
org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext()
this.reader = new AnnotatedBeanDefinitionReader(this);
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#AnnotatedBeanDefinitionReader(...)
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#getOrCreateEnvironment
org.springframework.context.support.AbstractApplicationContext#getEnvironment
return new StandardEnvironment();
org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)
org.springframework.context.annotation.AnnotationConfigUtils#unwrapDefaultListableBeanFactory
org.springframework.context.support.GenericApplicationContext#getDefaultListableBeanFactory
this.beanFactory = new DefaultListableBeanFactory()
org.springframework.beans.factory.support.DefaultListableBeanFactory#setDependencyComparator
new AnnotationAwareOrderComparator()
org.springframework.beans.factory.support.DefaultListableBeanFactory#setAutowireCandidateResolver
new ContextAnnotationAutowireCandidateResolver()
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
org.springframework.context.annotation.AnnotationConfigUtils#registerPostProcessor
注册6个postprocessor:()
ConfigurationClassPostProcessor
DefaultEventListenerFactory
EventListenerMethodProcessor
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor
this.scanner = new ClassPathBeanDefinitionScanner(this);
//初始化ClassPathBeanDefinitionScanner,设置filter和resourceLoader
org.springframework.context.annotation.ClassPathBeanDefinitionScanner#ClassPathBeanDefinitionScanner(org.springframework.beans.factory.support.BeanDefinitionRegistry, boolean, org.springframework.core.env.Environment, org.springframework.core.io.ResourceLoader)
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#setResourceLoader
org.springframework.core.io.support.ResourcePatternUtils#getResourcePatternResolver
this.resourcePatternResolver=ResourcePatternUtils.getResourcePatternResolver(resourceLoader);-》ResourcePatternResolver类型
this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
//把这个配置类的bean定义注册到beandeinition中
org.springframework.context.annotation.AnnotationConfigApplicationContext#register
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#registerBean(java.lang.Class<?>)
org.springframework.context.annotation.AnnotatedBeanDefinitionReader#registerBean(java.lang.Class<?>, java.lang.String, java.lang.Class<? extends java.lang.annotation.Annotation>...)
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
org.springframework.beans.factory.support.AbstractBeanDefinition#setBeanClass
this.metadata = new StandardAnnotationMetadata(beanClass, true);
org.springframework.core.type.StandardAnnotationMetadata#StandardAnnotationMetadata(java.lang.Class<?>, boolean)
this.annotations = introspectedClass.getAnnotations();
java.lang.Class#getAnnotations
java.lang.Class#annotationData
java.lang.Class#createAnnotationData
java.lang.Class#getRawAnnotations //解析class类定义,根据本地方法以及class常量池定义的数据来获取注解。同事也会解析父类中的注解
java.lang.Class#getConstantPool
sun.reflect.annotation.AnnotationParser#parseAnnotations
sun.reflect.annotation.AnnotationParser#parseAnnotations2
sun.reflect.annotation.AnnotationParser#parseAnnotation2
sun.reflect.annotation.AnnotationParser#parseSig
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry)
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
org.springframework.context.support.AbstractApplicationContext#refresh
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
org.springframework.context.support.AbstractApplicationContext#prepareRefresh
this.scanner.clearCache();
super.prepareRefresh();
this.closed.set(false);this.active.set(true); //原子操作类设置状态
// Initialize any placeholder property sources in the context environment
initPropertySources();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
refreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context. 调用factory processor 可以在bean未实例化前处理一些事情
invokeBeanFactoryPostProcessors(beanFactory);
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
if (beanFactory instanceof BeanDefinitionRegistry) {
//先给BeanFactoryPostProcessors排序,然后按照排序后的顺序依次执行
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
postProcessor.postProcessBeanDefinitionRegistry(registry);
processConfigBeanDefinitions(registry);
parser.parse(candidates);
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
processConfigurationClass(new ConfigurationClass(metadata, beanName));
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
//根据注解扫描所有的类
Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,componentScan.getBoolean("useDefaultFilters"),this.environment, this.resourdoScanceLoader);
return scanner.(StringUtils.toStringArray(basePackages));
//Perform a scan within the specified base packages,returning the registered bean definitions.
org.springframework.context.annotation.ClassPathBeanDefinitionScanner#doScan
//在此方法中找到需要扫描的路径下的所有class文件,然后转换成BeanDefinition
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
//获取所有的类文件
Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources
//在该方法中,一种会找目下的class文件,一种会找目下包中的,一种会找vfs的
findPathMatchingResources(locationPattern);
//此方法用来获取所有的文件根目录(直接在文件夹下的class,jar中的,vfs的) org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources
org.springframework.core.io.support.PathMatchingResourcePatternResolver#doFindAllClassPathResources
ClassLoader cl = getClassLoader();
org.springframework.core.io.support.PathMatchingResourcePatternResolver#convertClassLoaderURL
//读取直接在文件夹下的所有文件 org.springframework.core.io.support.PathMatchingResourcePatternResolver#doFindPathMatchingFileResources
rootDir = rootDirResource.getFile().getAbsoluteFile()
org.springframework.core.io.support.PathMatchingResourcePatternResolver#doFindMatchingFileSystemResources
Set<File> matchingFiles = retrieveMatchingFiles(rootDir, subPattern);
org.springframework.core.io.support.PathMatchingResourcePatternResolver#doRetrieveMatchingFiles
//循环执行doRetrieveMatchingFiles方法,直到找到该目录下的所有文件
//读取jar包中在此根目录下的文件 org.springframework.core.io.support.PathMatchingResourcePatternResolver#doFindPathMatchingJarResources(org.springframework.core.io.Resource, java.net.URL, java.lang.String)
URLConnection con = rootDirURL.openConnection();
JarURLConnection jarCon = (JarURLConnection) con;
JarFile jarFile = jarCon.getJarFile();
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {}
JarEntry entry = entries.nextElement();
org.springframework.core.io.UrlResource#createRelative
return new UrlResource(new URL(this.url, relativePath));
jarFile.close();
//开始把class文件转换为BeanDefinition
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
org.springframework.core.type.classreading.CachingMetadataReaderFactory#getMetadataReader
return new SimpleMetadataReader(resource,this.resourceLoader.getClassLoader());
ScannedGenericBeanDefinition sbd =new ScannedGenericBeanDefinition(metadataReader);
sbd.setResource(resource)
sbd.setSource(resource);
//
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
org.springframework.context.annotation.AnnotationBeanNameGenerator#generateBeanName
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
//Apply the provided default values to this bean.
org.springframework.beans.factory.support.AbstractBeanDefinition#applyDefaults
setLazyInit(defaults.isLazyInit());
setAutowireMode(defaults.getAutowireMode());
setInitMethodName(defaults.getInitMethodName());
setDestroyMethodName(defaults.getDestroyMethodName());
==
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<String>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
//对于已存在的,或先删除再注册
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
//找出每个类中依赖的类,并引入
parse(holder.getBeanDefinition().getBeanClassName(),holder.getBeanName());
processConfigurationClass(new ConfigurationClass(reader, beanName));
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), true);
//Returns {@code @Import} class, considering all meta-annotations.
org.springframework.context.annotation.ConfigurationClassParser#getImports
collectImports(sourceClass, imports, visited);
for (SourceClass annotation : sourceClass.getAnnotations()) {
String annName = annotation.getMetadata().getClassName();
if (!annName.startsWith("java") && !annName.equals(Import.class.getName())) {
collectImports(annotation, imports, visited);
}
}
// Process any @ImportResource annotations
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
// No superclass -> processing is complete
this.configurationClasses.put(configClass, configClass);
//搜索推迟的类
processDeferredImportSelectors();
//校验是否出错了
parser.validate();
this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor, this.resourceLoader,this.environment,this.importBeanNameGenerator, parser.getImportRegistry());
this.reader.loadBeanDefinitions(configClasses);
loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
if (registry.getBeanDefinitionCount() > candidateNames.length) {
//如果还没有注册就注册下
if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(beanDef.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(beanDef, candidateName));
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
prepareBeanFactory(beanFactory);