/** Map with String keys and Object values. */ privatefinalMap<String, Object> attributes=newLinkedHashMap<>();
@Nullable private Object source;
/** * Constant for the default scope name: {@code ""}, equivalent to singleton * status unless overridden from a parent bean definition (if applicable). * 默认bean作用域 */ publicstaticfinalStringSCOPE_DEFAULT="";
/** * Constant that indicates no external autowiring at all. * 自动注入模式 * @see #setAutowireMode */ publicstaticfinalintAUTOWIRE_NO= AutowireCapableBeanFactory.AUTOWIRE_NO;
/** * Constant that indicates autowiring bean properties by name. * 自动注入通过bean名字 * @see #setAutowireMode */ publicstaticfinalintAUTOWIRE_BY_NAME= AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
/** * Constant that indicates autowiring bean properties by type. * 自动注入通过bean类型 * @see #setAutowireMode */ publicstaticfinalintAUTOWIRE_BY_TYPE= AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
/** * Constant that indicates autowiring a constructor. * 自动注入通过构造函数 * @see #setAutowireMode */ publicstaticfinalintAUTOWIRE_CONSTRUCTOR= AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
/** * Constant that indicates determining an appropriate autowire strategy * through introspection of the bean class. * @see #setAutowireMode * @deprecated as of Spring 3.0: If you are using mixed autowiring strategies, * use annotation-based autowiring for clearer demarcation of autowiring needs. */ @Deprecated publicstaticfinalintAUTOWIRE_AUTODETECT= AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
/** * Constant that indicates no dependency check at all. * @see #setDependencyCheck */ publicstaticfinalintDEPENDENCY_CHECK_NONE=0;
/** * Constant that indicates dependency checking for object references. * @see #setDependencyCheck */ publicstaticfinalintDEPENDENCY_CHECK_OBJECTS=1;
/** * Constant that indicates dependency checking for "simple" properties. * @see #setDependencyCheck * @see org.springframework.beans.BeanUtils#isSimpleProperty */ publicstaticfinalintDEPENDENCY_CHECK_SIMPLE=2;
/** * Constant that indicates dependency checking for all properties * (object references as well as "simple" properties). * @see #setDependencyCheck */ publicstaticfinalintDEPENDENCY_CHECK_ALL=3;
/** * Constant that indicates the container should attempt to infer the * {@link #setDestroyMethodName destroy method name} for a bean as opposed to * explicit specification of a method name. The value {@value} is specifically * designed to include characters otherwise illegal in a method name, ensuring * no possibility of collisions with legitimately named methods having the same * name. * <p>Currently, the method names detected during destroy method inference * are "close" and "shutdown", if present on the specific bean class. */ publicstaticfinalStringINFER_METHOD="(inferred)";
/** Determines if the definition needs to be re-merged. */ volatileboolean stale;
booleanallowCaching=true;
booleanisFactoryMethodUnique=false;
@Nullable volatile ResolvableType targetType;
/** Package-visible field for caching the determined Class of a given bean definition. */ @Nullable volatile Class<?> resolvedTargetType;
/** Package-visible field for caching if the bean is a factory bean. */ @Nullable volatile Boolean isFactoryBean;
/** Package-visible field for caching the return type of a generically typed factory method. */ @Nullable volatile ResolvableType factoryMethodReturnType;
/** Package-visible field for caching a unique factory method candidate for introspection. */ @Nullable volatile Method factoryMethodToIntrospect;
/** Common lock for the four constructor fields below. */ finalObjectconstructorArgumentLock=newObject();
/** Package-visible field for caching the resolved constructor or factory method. */ @Nullable Executable resolvedConstructorOrFactoryMethod;
/** Package-visible field that marks the constructor arguments as resolved. */ booleanconstructorArgumentsResolved=false;
/** Package-visible field for caching fully resolved constructor arguments. */ @Nullable Object[] resolvedConstructorArguments;
/** Package-visible field for caching partly prepared constructor arguments. */ @Nullable Object[] preparedConstructorArguments;
/** Common lock for the two post-processing fields below. */ finalObjectpostProcessingLock=newObject();
/** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied. */ booleanpostProcessed=false;
/** Package-visible field that indicates a before-instantiation post-processor having kicked in. */ @Nullable volatile Boolean beforeInstantiationResolved;
Spring IoC容器对bean定义的加载是从refresh()方法开始的,这个方法是一个模板方法,它的作用是:在创建IoC容器前,如果已经有容器则把容器销毁关闭,然后再重新创建一个新的容器,然后再对容器做初始化。FileSystemXmlApplicationContext通过调用父类的AbstractApplicationContext.refresh()方法实现容器的创建,加载,初始等一系列操作。回到这个类的构造方法,可以看到在构造方法内部调用了refresh()方法。
publicvoidrefresh()throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. // 准备此上下文以进行刷新。 prepareRefresh();
// Tell the subclass to refresh the internal bean factory. // 获取beanFactory实例 ConfigurableListableBeanFactorybeanFactory= obtainFreshBeanFactory();
// Prepare the bean factory for use in this context. // 准备上下文使用的BeanFactory prepareBeanFactory(beanFactory);
try { // Allows post-processing of the bean factory in context subclasses. // 允许子类处理BeanFactory后置处理器 postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context. // 转到ConfigurationClassPostProcessor里面执行 // 执行bean工厂的后置处理器,里面会有非常多的,非常复杂的BeanFactoryPostProcessor实现类的执行。 invokeBeanFactoryPostProcessors(beanFactory);
// Destroy already created singletons to avoid dangling resources. destroyBeans();
// Reset 'active' flag. cancelRefresh(ex);
// Propagate exception to caller. throw ex; }
finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
/** * Loads the bean definitions via an XmlBeanDefinitionReader. * 通过XmlBeanDefinitionReader加载所有的bean定义, * 此方法在AbstractApplicationContext中定义了抽象,由子类实现。 * * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ @Override protectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. // 创建bean定义读取器,通过回调设置到容器中,不同的子类设置不同的读取器(有些是读取xml配置,有的是读取java代码的bean定义) XmlBeanDefinitionReaderbeanDefinitionReader=newXmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's // resource loading environment. // 加载上下文的环境配置,配置bean定义 beanDefinitionReader.setEnvironment(this.getEnvironment()); // 设置资源加载器, // 因为本类的最上层父类DefaultResourceLoader也继承了DefaultResourceLoader,所以可以直接传this。 beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. // 允许子类提供自定义的初始化读取器reader,然后处理加载bean定义 initBeanDefinitionReader(beanDefinitionReader); // 加载bean定义 loadBeanDefinitions(beanDefinitionReader); }
// 设置工厂的属性 if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) { factory.setValidating(true); if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) { // Enforce namespace aware for XSD... factory.setNamespaceAware(true); try { factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); } catch (IllegalArgumentException ex) { ParserConfigurationExceptionpcex=newParserConfigurationException( "Unable to validate using XSD: Your JAXP provider [" + factory + "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " + "Upgrade to Apache Xerces (or Java 1.5) for full XSD support."); pcex.initCause(ex); throw pcex; } } }
// beanName默认使用id属性的值,如果id属性为空,则获取name属性,如果name属性有多个值直接用第一个值作为beanName StringbeanName= id; if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); if (logger.isTraceEnabled()) { logger.trace("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases"); } }
// 进一步解析bean的其他所有属性并统一封装至GenericBeanDefinition类型实例中 AbstractBeanDefinitionbeanDefinition= parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName( beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name, if still possible, // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. StringbeanClassName= beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isTraceEnabled()) { logger.trace("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(), ele); returnnull; } } String[] aliasesArray= StringUtils.toStringArray(aliases); // 所有属性解析、校验完成后封装成BeanDefinitionHolder实例并返回 returnnewBeanDefinitionHolder(beanDefinition, beanName, aliasesArray); }
returnnull; }
@Nullable publicAbstractBeanDefinitionparseBeanDefinitionElement( Element ele, String beanName, @Nullable BeanDefinition containingBean) {
this.parseState.push(newBeanEntry(beanName));
// 解析class属性值 StringclassName=null; if (ele.hasAttribute(CLASS_ATTRIBUTE)) { className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); } // 解析parent属性值 Stringparent=null; if (ele.hasAttribute(PARENT_ATTRIBUTE)) { parent = ele.getAttribute(PARENT_ATTRIBUTE); }
protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. // 设置类加载器,存在则直接设置(一般是ApplicationClassLoader),不存在则创建一个新的默认加载器设置到容器中 // 不存在会一直往上找,一直找到java根加载器BoostrapClassLoader beanFactory.setBeanClassLoader(getClassLoader()); // 设置EL表达式解析器 beanFactory.setBeanExpressionResolver(newStandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 设置属性注册解析器 beanFactory.addPropertyEditorRegistrar(newResourceEditorRegistrar(this, getEnvironment()));
// 将当前的ApplicationContext对象交给ApplicationContextAwareProcessor类来处理, // 从而在Aware接口实现类中的注入applicationContext // Configure the bean factory with context callbacks. beanFactory.addBeanPostProcessor(newApplicationContextAwareProcessor(this));
// 注册自动装配使用到的类 // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 注册容器使用的监听器 // Register early post-processor for detecting inner beans as ApplicationListeners. beanFactory.addBeanPostProcessor(newApplicationListenerDetector(this));
//如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ, // 则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理, // 从而实现类加载期织入AspectJ的目的。 // Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// 注册当前容器环境environment组件Bean // Register default environment beans. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } // 注册当前电脑系统环境systemProperties组件Bean if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } // 注册当前电脑系统的环境变量信息systemEnvironment if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors=newArrayList<>();
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 不要再这里初始化FactoryBean,我们需要保留到所有未初始化的普通bean以便bean工厂后置处理可以处理 // 如果开启了注解方式(项目中使用<context:component-scan/>或者<context:annotation-config/>或者@ComponentScan注解), // 这里仍然可以获取到ConfigurationAnnotationProcessor, // 因为它也实现了BeanFactoryPostProcessor接口(postProcessBeanFactory()方法) String[] postProcessorNames= beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors=newArrayList<>(); List<String> orderedPostProcessorNames=newArrayList<>(); List<String> nonOrderedPostProcessorNames=newArrayList<>(); // 根据bean后置处理器的接口类型分类 for (String ppName : postProcessorNames) { // 排除前面已经执行过的bean工厂后置处理器(BeanDefinitionRegistryPostProcessor) if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } }
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 执行ConfigurationAnnotationProcessor的postProcessBeanFactory()方法 // 用于解析@Configuration注解的类中用@Bean注解的声明的bean,并把声明的bean转换BeanDefinition,注册到容器中 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered. List<BeanFactoryPostProcessor> orderedPostProcessors=newArrayList<>(orderedPostProcessorNames.size()); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors. List<BeanFactoryPostProcessor> nonOrderedPostProcessors=newArrayList<>(nonOrderedPostProcessorNames.size()); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } 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(); }
/** * 实现BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法。在 * @see org.springframework.context.support.AbstractApplicationContext 的refresh() -> invokeBeanFactoryPostProcessors()方法会调用, * 作用是往容器中注册bean定义,包括使用`@Component`/`@Service`/`@Controller`/`@Import`/`@Bean`等注解定义的类, * 这些类会被转换成BeanDefinition注册到容器中。 * Derive further bean definitions from the configuration classes in the registry. * 从注册表中的配置类派生更多的bean定义。 */ @Override publicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { intregistryId= System.identityHashCode(registry); if (this.registriesPostProcessed.contains(registryId)) { thrownewIllegalStateException( "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry); } if (this.factoriesPostProcessed.contains(registryId)) { thrownewIllegalStateException( "postProcessBeanFactory already called on this post-processor against " + registry); } this.registriesPostProcessed.add(registryId); // 非常重要的方法,在此方法内解析bean定义 processConfigBeanDefinitions(registry); }
// Read the model and create bean definitions based on its content // 在上下文中读取并创建bean定义 if (this.reader == null) { this.reader = newConfigurationClassBeanDefinitionReader( registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry()); } // 把配置类中配置的bean定义加载注册到容器 this.reader.loadBeanDefinitions(configClasses); alreadyParsed.addAll(configClasses);
candidates.clear(); // candidateNames包括了容器中的所有普通的bean定义(除了@Configuration注册的bean定义) // 再获取一下容器中的所有bean定义,如果有增加说明前面的已经有bean被解析并且注册到容器中 if (registry.getBeanDefinitionCount() > candidateNames.length) { String[] newCandidateNames= registry.getBeanDefinitionNames(); Set<String> oldCandidateNames=newHashSet<>(Arrays.asList(candidateNames)); Set<String> alreadyParsedClasses=newHashSet<>(); for (ConfigurationClass configurationClass : alreadyParsed) { alreadyParsedClasses.add(configurationClass.getMetadata().getClassName()); } for (String candidateName : newCandidateNames) { if (!oldCandidateNames.contains(candidateName)) { BeanDefinitionbd= registry.getBeanDefinition(candidateName); if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) && !alreadyParsedClasses.contains(bd.getBeanClassName())) { candidates.add(newBeanDefinitionHolder(bd, candidateName)); } } } candidateNames = newCandidateNames; } } while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); }
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { // Clear cache in externally provided MetadataReaderFactory; this is a no-op // for a shared cache since it'll be cleared by the ApplicationContext. ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); } }
/** * Apply processing and build a complete {@link ConfigurationClass} by reading the * annotations, members and methods from the source class. This method can be called * multiple times as relevant sources are discovered. * * 1. 一个配置类的成员类(配置类内嵌套定义的类)也可能适配类,先遍历这些成员配置类,调用processConfigurationClass处理它们; * 2. 处理配置类上的注解@PropertySources,@PropertySource * 3. 处理配置类上的注解@ComponentScans,@ComponentScan * 4. 处理配置类上的注解@Import * 5. 处理配置类上的注解@ImportResource * 6. 处理配置类中每个带有@Bean注解的方法 * 7. 处理配置类所实现接口的缺省方法 * 8. 检查父类是否需要处理,如果父类需要处理返回父类,否则返回null * * @param configClass the configuration class being build * @param sourceClass a source class * @return the superclass, or {@code null} if none found or previously processed */ @Nullable protectedfinalSourceClassdoProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
// 使用了@Configuration注解的类肯定是也是@Component注解的类,因为@Configuration继承了@Component if (configClass.getMetadata().isAnnotated(Component.class.getName())) { // Recursively process any member (nested) classes first // 默认情况下会执行进去,但是方法内判断会不通过,相当于没做任何事情 processMemberClasses(configClass, sourceClass); }
// Process any @PropertySource annotations // 2、处理属性资源文件,使用@PropertySource注解可以导入Properties属性文件 for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) { if (this.environment instanceof ConfigurableEnvironment) { processPropertySource(propertySource); } else { logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() + "]. Reason: Environment must implement ConfigurableEnvironment"); } }
// Process any @ComponentScan annotations // 处理@ComponentScan/@ComponentScans注解,获取注解上的属性值,比如basePackages属性值 Set<AnnotationAttributes> componentScans= AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class); if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { // 解析basePackages指定的包和子包下的类并转换成BeanDefinition for (AnnotationAttributes componentScan : componentScans) { // The config class is annotated with @ComponentScan -> perform the scan immediately Set<BeanDefinitionHolder> scannedBeanDefinitions= this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // Check the set of scanned definitions for any further config classes and parse recursively if needed for (BeanDefinitionHolder holder : scannedBeanDefinitions) { BeanDefinitionbdCand= holder.getBeanDefinition().getOriginatingBeanDefinition(); if (bdCand == null) { bdCand = holder.getBeanDefinition(); } // 如果扫描的basePackages指定的包和子包下的类还有使用了@Configuration注解则递归解析 if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) { parse(bdCand.getBeanClassName(), holder.getBeanName()); } } } }
// Process any @Import annotations // 处理@Import注解,@Import(MyImportSelector.class),MyImportSelector必须实现importSelector接口 /* 用法如下: public class MyImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[] { MyImportSelectorBean.class.getName() }; } } */ // @Import注解要和@Configuration一起用 processImports(configClass, sourceClass, getImports(sourceClass), true);
// Process any @ImportResource annotations // 处理 @ImportResource(locations={"classpath:applicationContext.xml"}) // @ImportResource注解要和@Configuration一起用 AnnotationAttributesimportResource= AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class); if (importResource != null) { String[] resources= importResource.getStringArray("locations"); Class<? extends BeanDefinitionReader> readerClass= importResource.getClass("reader"); for (String resource : resources) { StringresolvedResource=this.environment.resolveRequiredPlaceholders(resource); configClass.addImportedResource(resolvedResource, readerClass); } }
// 处理@Configuration配置类中使用@Bean注解的方法,比如: /** @Configuration public class AppConfig { @Bean public myServiceImpl() { return new MyServiceImpl(); } } */ // Process individual @Bean methods Set<MethodMetadata> beanMethods= retrieveBeanMethodMetadata(sourceClass); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(newBeanMethod(methodMetadata, configClass)); }
// Process default methods on interfaces processInterfaces(configClass, sourceClass);
// 处理配置类的父类,比如: /** public class AnnotationConfigApplicationContextConfig extends AnnotationConfigApplicationContextConfigParent { } public class AnnotationConfigApplicationContextConfigParent { @Bean public ParentConfigService parentConfigService() { return new ParentConfigService(); } } */ // Process superclass, if any if (sourceClass.getMetadata().hasSuperClass()) { Stringsuperclass= sourceClass.getMetadata().getSuperClassName(); // 排除java.xxx开头的包类,因为所有的类终究会继承顶层父类java.lang.Object。 if (superclass != null && !superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) { this.knownSuperclasses.put(superclass, configClass); // Superclass found, return its annotation metadata and recurse return sourceClass.getSuperClass(); } }
// No superclass -> processing is complete returnnull; }
// Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. intbeanProcessorTargetCount= beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(newBeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 根据BeanPostProcessor的实现不同区分开 // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors=newArrayList<>(); List<BeanPostProcessor> internalPostProcessors=newArrayList<>(); List<String> orderedPostProcessorNames=newArrayList<>(); List<String> nonOrderedPostProcessorNames=newArrayList<>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessorpp= beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); // 同时实现了PriorityOrdered接口和MergedBeanPostProcessor接口的实现类 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } }
// First, register the BeanPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered. List<BeanPostProcessor> orderedPostProcessors=newArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { BeanPostProcessorpp= beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); // 同时实现了Ordered接口和MergeBeanPostProcessor接口的 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); // 每次注册到容器时都是先删除再添加,所以不会重复 registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 重新注册,目的就是把此BeanPostProcessor放在数组末尾 beanFactory.addBeanPostProcessor(newApplicationListenerDetector(applicationContext)); }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 注册用户定义的监听器,比如com.ubuntuvim.spring.event.MyListener就是在这里注册的。 String[] listenerBeanNames= getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { // getApplicationEventMulticaster()拿到的就是refresh()方法中initApplicationEventMulticaster()定义的发布器 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); }
// Publish early application events now that we finally have a multicaster... Set<ApplicationEvent> earlyEventsToProcess=this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. // 初始化上下文的转换服务 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); }
// Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. // 如果前面没有注册配置解析器,则注入配置解析器,主要用来处理配置文件的占位符等 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames= beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. // 停止使用临时ClassLoader进行类型匹配 beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. // 冻结所有的Bean定义,在此后bean定义不会再被更改,因为在后面的方法就要开始根据bean定义创建bean实例了。 // 所有的bean定义在此后修改将是无任何效果的 beanFactory.freezeConfiguration();
/** * 实例化所有除了Spring内部的单例(懒加载的、抽象类、非单例的除外) */ @Override publicvoidpreInstantiateSingletons()throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); }
// Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. // 创建BeanDefinitionName副本,用于后续遍历,以允许init等方法注册新的bean定义 List<String> beanNames=newArrayList<>(this.beanDefinitionNames);
/** * Central method of this class: creates a bean instance, * populates the bean instance, applies post-processors, etc. * 本类的核心方法:创建bean实例,填充bean实例属性,应用(执行)后置处理, * 详细处理逻辑在doCreateBean方法实现 * @see #doCreateBean */ @Override protectedObjectcreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinitionmbdToUse= mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 通过Class.forName(bean)方法获取实例,合并bean定义 Class<?> resolvedClass= resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = newRootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } RootBeanDefinitionmbdToUse= mbd;
// Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. // 通过Class.forName(bean)方法获取实例,合并bean定义 Class<?> resolvedClass= resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = newRootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); }
// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 单例bean && 允许循环依赖 && bean正在被创建 booleanearlySingletonExposure= (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } /** * 执行后置处理器SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference()方法尝试获取一个早期的引用。 * 并加入的单例工厂缓存中 * @see DefaultSingletonBeanRegistry#addSingletonFactory(String, ObjectFactory) * @see #getEarlyBeanReference */ addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }
// Initialize the bean instance. // 初始化bean实例,填充属性,注入依赖(@Autowired,@Resource,@Value)注解的属性 ObjectexposedObject= bean; try { populateBean(beanName, mbd, instanceWrapper); /** 执行bean的初始化回调方法以及执行后置处理器的初始化方法,包括: 一,执行Aware接口 ,包括BeanFactoryAware,BeanClassLoaderAware,BeanNameAware 注意:ApplicationContext的注入是在另外一个后置处理器ApplicationContextAwareProcessor中执行。 二,执行bean初始化回调,包括: 0. 执行初始化回调BeanPostProcessor.postProcessBeforeInitialization()方法 1. 执行初始化回调@PostConstruct注解定义的方法 2. 执行初始化回调InitializingBean.afterPropertiesSet()方法 3. 执行初始化回调@Bean(initMethod = "beanInit")定义的初始化方法beanInit() 4. 执行初始化回调BeanPostProcessor.postProcessAfterInitialization()方法 5. 执行初始化回调SmartInitializingSingleton.afterSingletonsInstantiated()方法 按照上述执行顺序执行 */ exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } // 循环依赖检查 if (earlySingletonExposure) { ObjectearlySingletonReference= getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } elseif (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans= getDependentBeans(beanName); Set<String> actualDependentBeans=newLinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { thrownewBeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } }
protectedBeanWrappercreateBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. Class<?> beanClass= resolveBeanClass(mbd, beanName);
// 检查bean的访问类型,比如是public并且是非final if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { thrownewBeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } // 存在Supplier回调则使用回调里的方法创建实例(jdk1.8)之后的才有的特性 // 通过instanceSupplier.get()方法返回实例 Supplier<?> instanceSupplier= mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } // 通过工厂方法创建实例 if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); }
// Shortcut when re-creating the same bean... // 通过constructorArgumentsResolved标记起到了缓存的作用 // 当容器创建同一个类型bean的时候(非单例情况),可以直接使用构造器创建,不需要再此解析构造器上的参数。 // 参数的解析的开销也是不小的。 booleanresolved=false; booleanautowireNecessary=false; if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; // constructorArgumentsResolved标记了构造器的参数都已经解析完成 autowireNecessary = mbd.constructorArgumentsResolved; } } } if (resolved) { if (autowireNecessary) { /** * 通过有参构造方法创建,并自动注入构造方法中的参数值,如果有对象依赖在方法内部又会调getBean()方法创建bean实例 * 然后注入到对应的属性上。比如这个bean,构造方法引用了另外一个RefrenceBeanA * @see com.ubuntuvim.spring.createbean.HasArgsConstructBean * <pre> * @Component * public class HasArgsConstructBean { * private RefrenceBeanA refrenceBeanA; * * public HasArgsConstructBean(RefrenceBeanA refrenceBeanA) { * this.refrenceBeanA = refrenceBeanA; * } * } * </pre> */ return autowireConstructor(beanName, mbd, null, null); } else { // 使用默认的无参构造方法创建实例,底层使用反射newInstance()方法创建对象 return instantiateBean(beanName, mbd); } }
protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { // 前面创建的bean实例为空时 if (bw == null) { if (mbd.hasPropertyValues()) { thrownewBeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. // 当前bean实例都是null也就无法填充属性值了,直接返回 return; } }
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. // 执行后置处理器InstantiationAwareBeanPostProcessor,提供一个机会让开发者可以在bean实例化后,初始化前做一些操作。 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessoribp= (InstantiationAwareBeanPostProcessor) bp; // 如果返回false则直接退出当前方法,不进行下面的属性填充操作,所以一定要非常注意后置处理器的返回值以及执行顺序。 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } // 获取属性值 PropertyValuespvs= (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 获取注入模式(byType或者byName) intresolvedAutowireMode= mbd.getResolvedAutowireMode(); if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { // 把属性值再做一次包装,转换成一个MutablePropertyValues对象。 MutablePropertyValuesnewPvs=newMutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 如果适用,根据类型添加基于自动装配的属性值。 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. // 如果适用,根据类型添加基于自动装配的属性值。 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } // 存在InstantiationAwareBeanPostProcessor后置处理器 booleanhasInstAwareBpps= hasInstantiationAwareBeanPostProcessors();
// Don't let calling code try to dereference the factory if the bean isn't a factory. // 如果不是FactoryBean,为了以防开发者自定义的bean名字也加了&前缀,因为Spring默认&开头的bean是工厂bean if (BeanFactoryUtils.isFactoryDereference(name)) { if (beanInstance instanceof NullBean) { return beanInstance; } if (!(beanInstance instanceof FactoryBean)) { thrownewBeanIsNotAFactoryException(beanName, beanInstance.getClass()); } if (mbd != null) { mbd.isFactoryBean = true; } return beanInstance; }
// Now we have the bean instance, which may be a normal bean or a FactoryBean. // If it's a FactoryBean, we use it to create a bean instance, unless the // caller actually wants a reference to the factory. // 如果不是FactoryBean则无需通过调用getObject方法获取实例, // 正常情况下普通的bean已经在前面的doCreateBean方法中创建好了 if (!(beanInstance instanceof FactoryBean)) { return beanInstance; }
Objectobject=null; if (mbd != null) { mbd.isFactoryBean = true; } else { // 从FactoryBean对象缓存中获取 object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. // 获取工厂bean实例本身 FactoryBean<?> factory= (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) { mbd = getMergedLocalBeanDefinition(beanName); } booleansynthetic= (mbd != null && mbd.isSynthetic()); // 调用工厂bean的getObject方法获取对象实例 object = getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; }
// Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. // 不接受null对象,如果开发者实现了FactoryBean接口,但是在getObject方法中返回了null,那么Spring会默认返回的一个NullBean对象实例 if (object == null) { if (isSingletonCurrentlyInCreation(beanName)) { thrownewBeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } object = newNullBean(); } return object; }
protectedvoidfinishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). clearResourceCaches();
// Initialize lifecycle processor for this context. // 初始化容器生命周期处理器 initLifecycleProcessor();
// Propagate refresh to lifecycle processor first. // 执行实现fecycleProcessor接口的onRefresh()方法 getLifecycleProcessor().onRefresh();
// Publish the final event. // 通过initApplicationEventMulticaster()方法注册事件发布器,给registerListeners()方法注册的监听器发布事件, // 事件的发布说白就是遍历所有的监听器,调用ApplicationListener接口的onApplicationEvent方法 publishEvent(newContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext(this); }