AnnotationConfigApplicationContext容器初始化
AnnotationConfigApplicationContext容器初始化目錄
 (Spring源碼分析)AnnotationConfigApplicationContext容器初始化 this() && register()
 (Spring源碼分析)AnnotationConfigApplicationContext容器初始化 refresh()#invokeBeanFactoryPostProcessors
 (Spring源碼分析)AnnotationConfigApplicationContext容器初始化 refresh()#registerBeanPostProcessors
 (Spring源碼分析)AnnotationConfigApplicationContext容器初始化 refresh()#finishBeanFactoryInitialization
 ?
使用AnnotationConfigApplicationContext容器
public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);TestService testService = applicationContext.getBean(TestService.class);System.out.println(testService.sout()); }AppConfig配置類
@Configuration @ComponentScan("com.leon.learning.build.applicationcontext") public class AppConfig { }AnnotationConfigApplicationContext容器方法
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);這段代碼會調(diào)用AnnotationConfigApplicationContext類的無參構(gòu)造方法
 ?
AnnotationConfigApplicationContext容器方法
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);這段代碼會調(diào)用AnnotationConfigApplicationContext類的無參構(gòu)造方法
/*** 這個構(gòu)造方法需要傳入一個javaconfig注解了的配置類* 然后會把這個被注解了javaconfig的類通過注解讀取器讀取后繼而解析*/ public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {// 這里由于他有父類,故而會先調(diào)用父類的無參構(gòu)造方法,然后才會調(diào)用自己的無參構(gòu)造方法// 在自己構(gòu)造方法中初始一個讀取器和掃描器this();register(annotatedClasses); // 這里僅僅只是將annotatedClasses作為bean放入beanDefinitionMap中refresh(); // AnnotationConfigApplicationContext容器中最重要的方法,將annotatedClasses中 掃描的bean加入beanDefinitionMap中 }1、this()
this()方法主要是初始化BeanFactory容器在AnnotationConfigApplicationContext父類GenericApplicationContext的無參構(gòu)造方法中
/*** 初始化BeanFactory*/ public GenericApplicationContext() {this.beanFactory = new DefaultListableBeanFactory(); }然后執(zhí)行AnnotationConfigApplicationContext自己的無參構(gòu)造方法
/*** 初始化注解讀取器和掃描器*/ public AnnotationConfigApplicationContext() {this.reader = new AnnotatedBeanDefinitionReader(this);this.scanner = new ClassPathBeanDefinitionScanner(this); }2、register(annotatedClasses)
register(annotatedClasses)方法主要是將傳入的配置類加入到BeanDefinitionMap中,但是配置類中配置 的包掃描路徑下的bean并沒有添加到BeanDefinitionMap中 /*** 判斷annotatedClasses不為空,并調(diào)用AnnotatedBeanDefinitionReader注解讀取器去讀取配置類 annotatedClasses中的配置*/ public void register(Class<?>... annotatedClasses) {Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");this.reader.register(annotatedClasses); // 調(diào)用AnnotatedBeanDefinitionReader注解讀取器去讀 取配置類annotatedClasses中的配置 }2.1、this.reader.register(annotatedClasses)
/*** 循環(huán)調(diào)用AnnotatedBeanDefinitionReader注解讀取器去讀取配置類*/ public void register(Class<?>... annotatedClasses) {for (Class<?> annotatedClass : annotatedClasses) {registerBean(annotatedClass);} }2.1.1、registerBean(annotatedClass)
public void registerBean(Class<?> annotatedClass) {doRegisterBean(annotatedClass, null, null, null); }2.1.1.1、doRegisterBean(annotatedClass, null, null, null)
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {// 這里的這個AnnotatedGenericBeanDefinition對象僅僅只是在new AnnotationConfigApplicationContext(傳入的配置類)AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass); // 將Bean的配置信息轉(zhuǎn)換成AnnotatedGenericBeanDefinition,它繼承了BeanDefinition接口,包含bean的屬性// @Conditional裝配條件判斷是否需要跳過注冊if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {return;}abd.setInstanceSupplier(instanceSupplier);ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd); // 解析bean作用域,如果使有@Scope注解指定了bean的作用域?qū)⒃O(shè)置成指定的作用域,否則默認(rèn)為singleton(單例)abd.setScope(scopeMetadata.getScopeName()); // 為AnnotatedGenericBeanDefinition對象設(shè)置scope(作用域)屬性String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry)); // 生成beanNameAnnotationConfigUtils.processCommonDefinitionAnnotations(abd); // 解析AnnotatedGenericBeanDefinition對象中l(wèi)azy、Primary、DependsOn、Role、Description屬性if (qualifiers != null) { // @Qualifier特殊限定符處理for (Class<? extends Annotation> qualifier : qualifiers) {if (Primary.class == qualifier) {abd.setPrimary(true);}else if (Lazy.class == qualifier) {abd.setLazyInit(true);}else {abd.addQualifier(new AutowireCandidateQualifier(qualifier));}}}// 處理applicationcontext容器加載完成后手動registerBeanfor (BeanDefinitionCustomizer customizer : definitionCustomizers) {customizer.customize(abd);}BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName); // 將beanName和AnnotatedGenericBeanDefinition封裝在BeanDefinitionHolder中definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 創(chuàng)建代理對象BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry); // 將BeanDefinition注冊到BeanDefinitionMap中 }2.1.1.1.1、BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry)
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)throws BeanDefinitionStoreException {// Register bean definition under primary name.String beanName = definitionHolder.getBeanName();registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // 調(diào)用BeanDefinitionRegistry方法對BeanDefinition注冊到ConCurrentHashMap中// Register aliases for bean name, if any.String[] aliases = definitionHolder.getAliases();if (aliases != null) {for (String alias : aliases) {registry.registerAlias(beanName, alias); // 注冊別名}} }2.1.1.1.1.1、registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition())
/*** 對BeanDefinition注冊到ConCurrentHashMap中*/ @Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)throws BeanDefinitionStoreException {// 校驗beanName和beanDefinition不能為空Assert.hasText(beanName, "Bean name must not be empty");Assert.notNull(beanDefinition, "BeanDefinition must not be null");// beanDefinition校驗if (beanDefinition instanceof AbstractBeanDefinition) {try {((AbstractBeanDefinition) beanDefinition).validate();}catch (BeanDefinitionValidationException ex) {throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,"Validation of bean definition failed", ex);}}BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); // 判斷beanDefinitionMap中是否含有相同beanName的BeanDefinition// 如果beanDefinitionMap中存在相同beanName的BeanDefinitionif (existingDefinition != null) {// 判斷是否允許含有同樣的beanName對BeanDefinition進(jìn)行覆蓋if (!isAllowBeanDefinitionOverriding()) {throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +"': There is already [" + existingDefinition + "] bound.");}// 參數(shù)校驗else if (existingDefinition.getRole() < beanDefinition.getRole()) {// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTUREif (logger.isWarnEnabled()) {logger.warn("Overriding user-defined bean definition for bean '" + beanName +"' with a framework-generated bean definition: replacing [" +existingDefinition + "] with [" + beanDefinition + "]");}}else if (!beanDefinition.equals(existingDefinition)) {if (logger.isInfoEnabled()) {logger.info("Overriding bean definition for bean '" + beanName +"' with a different definition: replacing [" + existingDefinition +"] with [" + beanDefinition + "]");}}else {if (logger.isDebugEnabled()) {logger.debug("Overriding bean definition for bean '" + beanName +"' with an equivalent definition: replacing [" + existingDefinition +"] with [" + beanDefinition + "]");}}this.beanDefinitionMap.put(beanName, beanDefinition); // 將beanName和beanDefinition存到beanDefinitionMap中}// 如果beanDefinitionMap中不存在相同beanName的BeanDefinitionelse {if (hasBeanCreationStarted()) {// Cannot modify startup-time collection elements anymore (for stable iteration)synchronized (this.beanDefinitionMap) { // 同步代碼塊this.beanDefinitionMap.put(beanName, beanDefinition); // 將beanName和beanDefinition存到beanDefinitionMap中List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);updatedDefinitions.addAll(this.beanDefinitionNames);updatedDefinitions.add(beanName);this.beanDefinitionNames = updatedDefinitions;if (this.manualSingletonNames.contains(beanName)) {Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);updatedSingletons.remove(beanName);this.manualSingletonNames = updatedSingletons;}}}else {// Still in startup registration phasethis.beanDefinitionMap.put(beanName, beanDefinition);this.beanDefinitionNames.add(beanName);this.manualSingletonNames.remove(beanName);}this.frozenBeanDefinitionNames = null;}if (existingDefinition != null || containsSingleton(beanName)) {resetBeanDefinition(beanName);} }refresh()
在refresh()中,主要有12個方法,下面主要對invokeBeanFactoryPostProcessors(beanFactory)、 registerBeanPostProcessors(beanFactory)、finishBeanFactoryInitialization(beanFactory)方法進(jìn) 行分析 @Override public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// 準(zhǔn)備工作包括設(shè)置啟動時間,是否激活標(biāo)識位// 1.刷新預(yù)處理的前期準(zhǔn)備prepareRefresh();// 2.獲取內(nèi)部的Bean工廠ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// 3.準(zhǔn)備需要刷新后的工廠,為beanFactory屬性設(shè)置初始值prepareBeanFactory(beanFactory);try {// 4.這個方法在當(dāng)前版本的Spring是沒用,留著給擴(kuò)展使用postProcessBeanFactory(beanFactory);// 5.在Spring的環(huán)境中去執(zhí)行已經(jīng)被注冊的factory processors// 設(shè)置執(zhí)行自定的ProcessBeanFactory和Spring內(nèi)部自己定義的// 把類給掃描出來、處理@Import、@ImportSource導(dǎo)入資源文件,處理MapperScan// scan -- put beanDefinitionMapinvokeBeanFactoryPostProcessors(beanFactory);// 6.注冊beanPostProcessorregisterBeanPostProcessors(beanFactory);// 7.初始化MessageSourceinitMessageSource();// 8.初始化應(yīng)用實踐廣播器initApplicationEventMulticaster();// 9.這個方法在當(dāng)前版本的Spring是沒用,留著給擴(kuò)展使用onRefresh();// 10.Check for listener beans and register them.registerListeners();// 11.new對象,單例,將beanFactory中的beanDefinitionMap中的bean進(jìn)行初始化,然后放到單例池singletonObjects中finishBeanFactoryInitialization(beanFactory);// 12.Last step: publish corresponding event.finishRefresh();}catch (BeansException ex) {if (logger.isWarnEnabled()) {logger.warn("Exception encountered during context initialization - " +"cancelling refresh attempt: " + ex);}// 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();}} }invokeBeanFactoryPostProcessors(beanFactory)
invokeBeanFactoryPostProcessors(beanFactory)主要是作用如下:
在Spring的環(huán)境中去執(zhí)行已經(jīng)被注冊的BeanFactoryPostProcessors 設(shè)置執(zhí)行Spring內(nèi)部自己定義的BeanFactoryPostProcessors 將配置類中的bean掃描出來,添加到BeanDefinitionMap中 處理@Import、@ImportSource導(dǎo)入資源文件 protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());// 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(new LoadTimeWeaverAwareProcessor(beanFactory));beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));} }invokeBeanFactoryPostProcessors(beanFactory, beanFactoryPostProcessors)
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {// Invoke BeanDefinitionRegistryPostProcessors first, if any.Set<String> processedBeans = new HashSet<>();if (beanFactory instanceof BeanDefinitionRegistry) {BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); // 用來存放實現(xiàn)BeanFactoryPostProcessor接口的類List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); // 用來存放實現(xiàn)BeanDefinitionRegistryPostProcessor接口的類// 遍歷beanFactoryPostProcessors,如果是實現(xiàn)BeanDefinitionRegistryPostProcessor的,直接執(zhí)行實現(xiàn)類中實現(xiàn)的postProcessBeanDefinitionRegistry方法for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {BeanDefinitionRegistryPostProcessor registryProcessor =(BeanDefinitionRegistryPostProcessor) postProcessor;registryProcessor.postProcessBeanDefinitionRegistry(registry);registryProcessors.add(registryProcessor);}else {regularPostProcessors.add(postProcessor);}}// 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 = new ArrayList<>(); // 用來存放beanDefinitionMap中繼承了BeanDefinitionRegistryPostProcessor接口的bean// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.// 查找beanDefinitionMap中繼承了BeanDefinitionRegistryPostProcessor接口的beanString[] postProcessorNames =beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors); // 將beanDefinitionMap中繼承了BeanDefinitionRegistryPostProcessor接口的bean添加到registryProcessors以便后面執(zhí)行postProcessBeanFactory方法invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.boolean reiterate = true;while (reiterate) {reiterate = false;postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);reiterate = true;}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);currentRegistryProcessors.clear();}// Now, invoke the postProcessBeanFactory callback of all processors handled so far.// 執(zhí)行實現(xiàn)了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口實現(xiàn)的postProcessBeanFactory方法invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);}else {// Invoke factory processors registered with the context instance.invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,// Ordered, and the rest.List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();List<String> orderedPostProcessorNames = new ArrayList<>();List<String> nonOrderedPostProcessorNames = new ArrayList<>();for (String ppName : postProcessorNames) {if (processedBeans.contains(ppName)) {// skip - already processed in first phase above}else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));}else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);}else {nonOrderedPostProcessorNames.add(ppName);}}// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory);invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);// Next, invoke the BeanFactoryPostProcessors that implement Ordered.List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();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 = new ArrayList<>();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(); }invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry)
private static void invokeBeanDefinitionRegistryPostProcessors(Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {// 執(zhí)行postProcessors中實現(xiàn)了BeanFactoryPostProcessor接口中的postProcessBeanDefinitionRegistry方法for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {postProcessor.postProcessBeanDefinitionRegistry(registry);} }postProcessor.postProcessBeanDefinitionRegistry(registry)
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {int registryId = System.identityHashCode(registry); // 獲取registryIdif (this.registriesPostProcessed.contains(registryId)) {throw new IllegalStateException("postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);}if (this.factoriesPostProcessed.contains(registryId)) {throw new IllegalStateException("postProcessBeanFactory already called on this post-processor against " + registry);}this.registriesPostProcessed.add(registryId);processConfigBeanDefinitions(registry); }processConfigBeanDefinitions(registry)
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {List<BeanDefinitionHolder> configCandidates = new ArrayList<>();String[] candidateNames = registry.getBeanDefinitionNames(); // 取出beanDefinition的className數(shù)組// 遍歷beanDefinition的className數(shù)組for (String beanName : candidateNames) {BeanDefinition beanDef = registry.getBeanDefinition(beanName); // 取出BeanDefinitionif (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {if (logger.isDebugEnabled()) {logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);}}else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { // 檢查該BeanDefinition對象是否被@Configuration注解標(biāo)識configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));}}// Return immediately if no @Configuration classes were foundif (configCandidates.isEmpty()) {return;}// Sort by previously determined @Order value, if applicableconfigCandidates.sort((bd1, bd2) -> {int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());return Integer.compare(i1, i2);});// Detect any custom bean name generation strategy supplied through the enclosing application contextSingletonBeanRegistry sbr = null;if (registry instanceof SingletonBeanRegistry) {sbr = (SingletonBeanRegistry) registry;if (!this.localBeanNameGeneratorSet) {BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);if (generator != null) {this.componentScanBeanNameGenerator = generator;this.importBeanNameGenerator = generator;}}}if (this.environment == null) {this.environment = new StandardEnvironment();}// Parse each @Configuration classConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment,this.resourceLoader, this.componentScanBeanNameGenerator, registry); // 創(chuàng)建Configuration配置解析器Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());do {parser.parse(candidates); // 解析帶有@Configuration標(biāo)識的配置beanparser.validate();Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());configClasses.removeAll(alreadyParsed);// Read the model and create bean definitions based on its contentif (this.reader == null) {this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor, this.resourceLoader, this.environment,this.importBeanNameGenerator, parser.getImportRegistry());}this.reader.loadBeanDefinitions(configClasses);alreadyParsed.addAll(configClasses);candidates.clear();if (registry.getBeanDefinitionCount() > candidateNames.length) {String[] newCandidateNames = registry.getBeanDefinitionNames();Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));Set<String> alreadyParsedClasses = new HashSet<>();for (ConfigurationClass configurationClass : alreadyParsed) {alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());}for (String candidateName : newCandidateNames) {if (!oldCandidateNames.contains(candidateName)) {BeanDefinition bd = registry.getBeanDefinition(candidateName);if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&!alreadyParsedClasses.contains(bd.getBeanClassName())) {candidates.add(new BeanDefinitionHolder(bd, candidateName));}}}candidateNames = newCandidateNames;}}while (!candidates.isEmpty());// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classesif (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();} }parser.parse(candidates)
public void parse(Set<BeanDefinitionHolder> configCandidates) {this.deferredImportSelectors = new LinkedList<>();for (BeanDefinitionHolder holder : configCandidates) {BeanDefinition bd = holder.getBeanDefinition();try {if (bd instanceof AnnotatedBeanDefinition) { // 該BeanDefinition的實現(xiàn)類是AnnotatedBeanDefinitionparse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName()); // getMetadata()是獲取該AnnotatedBeanDefinition對象中的所有的注解}else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());}else {parse(bd.getBeanClassName(), holder.getBeanName());}}catch (BeanDefinitionStoreException ex) {throw ex;}catch (Throwable ex) {throw new BeanDefinitionStoreException("Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);}}processDeferredImportSelectors(); }processConfigurationClass(new ConfigurationClass(metadata, beanName))
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {return;}ConfigurationClass existingClass = this.configurationClasses.get(configClass);if (existingClass != null) {if (configClass.isImported()) {if (existingClass.isImported()) {existingClass.mergeImportedBy(configClass);}// Otherwise ignore new imported config class; existing non-imported class overrides it.return;}else {// Explicit bean definition found, probably replacing an import.// Let's remove the old one and go with the new one.this.configurationClasses.remove(configClass);this.knownSuperclasses.values().removeIf(configClass::equals);}}// Recursively process the configuration class and its superclass hierarchy.// 遞歸處理配置類和它的父類SourceClass sourceClass = asSourceClass(configClass);do {sourceClass = doProcessConfigurationClass(configClass, sourceClass);}while (sourceClass != null);this.configurationClasses.put(configClass, configClass); }doProcessConfigurationClass(configClass, sourceClass)
@Nullable protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)throws IOException {// Recursively process any member (nested) classes firstprocessMemberClasses(configClass, sourceClass);// Process any @PropertySource annotations// 判斷sourceClass的注解中是否有@PropertySource注解for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), PropertySources.class,org.springframework.context.annotation.PropertySource.class)) {if (this.environment instanceof ConfigurableEnvironment) {processPropertySource(propertySource);}else {logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +"]. Reason: Environment must implement ConfigurableEnvironment");}}// Process any @ComponentScan annotations// 判斷sourceClass的注解中是否有@ComponentScan注解Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);if (!componentScans.isEmpty() &&!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { // @ComponentScan注解可以在同一個配置類中使用多次for (AnnotationAttributes componentScan : componentScans) {// The config class is annotated with @ComponentScan -> perform the scan immediatelySet<BeanDefinitionHolder> scannedBeanDefinitions =this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // 使用ComponentScanAnnotationParser解析器去掃描并注冊該bean// Check the set of scanned definitions for any further config classes and parse recursively if neededfor (BeanDefinitionHolder holder : scannedBeanDefinitions) {BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();if (bdCand == null) {bdCand = holder.getBeanDefinition();}if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {parse(bdCand.getBeanClassName(), holder.getBeanName());}}}}// Process any @Import annotationsprocessImports(configClass, sourceClass, getImports(sourceClass), true);// Process any @ImportResource annotationsAnnotationAttributes importResource =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) {String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);configClass.addImportedResource(resolvedResource, readerClass);}}// Process individual @Bean methodsSet<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);for (MethodMetadata methodMetadata : beanMethods) {configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));}// Process default methods on interfacesprocessInterfaces(configClass, sourceClass);// Process superclass, if anyif (sourceClass.getMetadata().hasSuperClass()) {String superclass = sourceClass.getMetadata().getSuperClassName();if (superclass != null && !superclass.startsWith("java") &&!this.knownSuperclasses.containsKey(superclass)) {this.knownSuperclasses.put(superclass, configClass);// Superclass found, return its annotation metadata and recursereturn sourceClass.getSuperClass();}}// No superclass -> processing is completereturn null; }this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName())
/*** 得到basePackages*/ public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :BeanUtils.instantiateClass(generatorClass));ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");if (scopedProxyMode != ScopedProxyMode.DEFAULT) {scanner.setScopedProxyMode(scopedProxyMode);}else {Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));}scanner.setResourcePattern(componentScan.getString("resourcePattern"));for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {for (TypeFilter typeFilter : typeFiltersFor(filter)) {scanner.addIncludeFilter(typeFilter);}}for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {for (TypeFilter typeFilter : typeFiltersFor(filter)) {scanner.addExcludeFilter(typeFilter);}}boolean lazyInit = componentScan.getBoolean("lazyInit");if (lazyInit) {scanner.getBeanDefinitionDefaults().setLazyInit(true);}Set<String> basePackages = new LinkedHashSet<>();String[] basePackagesArray = componentScan.getStringArray("basePackages");for (String pkg : basePackagesArray) {String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);Collections.addAll(basePackages, tokenized);}for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {basePackages.add(ClassUtils.getPackageName(clazz));}if (basePackages.isEmpty()) {basePackages.add(ClassUtils.getPackageName(declaringClass));}scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {@Overrideprotected boolean matchClassName(String className) {return declaringClass.equals(className);}});return scanner.doScan(StringUtils.toStringArray(basePackages)); // 掃描指定路徑下的bean }scanner.doScan(StringUtils.toStringArray(basePackages))
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {Assert.notEmpty(basePackages, "At least one base package must be specified");Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();// 循環(huán)basePackagefor (String basePackage : basePackages) {Set<BeanDefinition> candidates = findCandidateComponents(basePackage); // 掃描basePackage路徑下所有的bean,返回BeanDefinition對象Set集合for (BeanDefinition candidate : candidates) {ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);candidate.setScope(scopeMetadata.getScopeName());String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);if (candidate instanceof AbstractBeanDefinition) {postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);}if (candidate instanceof AnnotatedBeanDefinition) {AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);}if (checkCandidate(beanName, candidate)) {BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);definitionHolder =AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);beanDefinitions.add(definitionHolder);registerBeanDefinition(definitionHolder, this.registry); // 注冊bean到beanDefinitionMap中}}}return beanDefinitions; }registerBeanDefinition(definitionHolder, this.registry)
看到BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry)這個方法調(diào) 用,其實就是在上一節(jié)已經(jīng)講過了,就是將bean注冊到BeanDefinitionMap中 protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry); }registerBeanPostProcessors(beanFactory)
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }?
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this)
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {// 查詢beanDefinitionMap中所有實現(xiàn)了BeanPostProcessor接口的類名稱數(shù)組String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);// 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.// 將beanFactory作為BeanPostProcessors作為后置處理器添加到的beanPostProcessors中int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));// Separate between BeanPostProcessors that implement PriorityOrdered,// Ordered, and the rest.// 對實現(xiàn)了不同接口的后置處理器進(jìn)行分類List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();List<String> orderedPostProcessorNames = new ArrayList<>();List<String> nonOrderedPostProcessorNames = new ArrayList<>();for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);priorityOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);}else {nonOrderedPostProcessorNames.add(ppName);}}// 注冊實現(xiàn)了PriorityOrdered接口的處理器// First, register the BeanPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);// Next, register the BeanPostProcessors that implement Ordered.// 注冊實現(xiàn)了Ordered接口的處理器List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();for (String ppName : orderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);orderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}sortPostProcessors(orderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, orderedPostProcessors);// Now, register all regular BeanPostProcessors.// 注冊既沒有實現(xiàn)PriorityOrdered接口的也沒有實現(xiàn)Ordered接口的處理器List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();for (String ppName : nonOrderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);nonOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);// Finally, re-register all internal BeanPostProcessors.// 最后,重新注冊所有的后置處理器sortPostProcessors(internalPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, internalPostProcessors);// Re-register post-processor for detecting inner beans as ApplicationListeners,// moving it to the end of the processor chain (for picking up proxies etc).beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors)
private static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {for (BeanPostProcessor postProcessor : postProcessors) {beanFactory.addBeanPostProcessor(postProcessor);} }beanFactory.addBeanPostProcessor(postProcessor)
@Override public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");// Remove from old position, if anythis.beanPostProcessors.remove(beanPostProcessor);// Track whether it is instantiation/destruction awareif (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {this.hasInstantiationAwareBeanPostProcessors = true;}if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {this.hasDestructionAwareBeanPostProcessors = true;}// Add to end of listthis.beanPostProcessors.add(beanPostProcessor); }finishBeanFactoryInitialization(beanFactory)
protected void finishBeanFactoryInitialization(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.beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.// 初始化非懶加載的beanbeanFactory.preInstantiateSingletons(); }beanFactory.preInstantiateSingletons()
@Override public void preInstantiateSingletons() throws BeansException {if (logger.isDebugEnabled()) {logger.debug("Pre-instantiating singletons in " + this);}// 所有bean的beanName// 可能需要實例化的class(lazy、scope):懶加載的不實例化,非單例的不實例化List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);// 觸發(fā)所有非延遲加載單例beans的初始化,主要步驟為調(diào)用getBean()方法來對bean進(jìn)行初始化for (String beanName : beanNames) {RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 當(dāng)BeanDefinition是抽象的,并且不是單例的,并且是懶加載的就不實例化beanif (isFactoryBean(beanName)) { // 當(dāng)該bean繼承了FactoryBean時Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);if (bean instanceof FactoryBean) {final FactoryBean<?> factory = (FactoryBean<?>) bean;boolean isEagerInit;if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());}else {isEagerInit = (factory instanceof SmartFactoryBean &&((SmartFactoryBean<?>) factory).isEagerInit());}if (isEagerInit) {getBean(beanName);}}}else {getBean(beanName); // 初始化該bean}}}// Trigger post-initialization callback for all applicable beans...for (String beanName : beanNames) {Object singletonInstance = getSingleton(beanName);if (singletonInstance instanceof SmartInitializingSingleton) {final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {smartSingleton.afterSingletonsInstantiated();return null;}, getAccessControlContext());}else {smartSingleton.afterSingletonsInstantiated();}}} }getBean(beanName)
@Override public Object getBean(String name) throws BeansException {return doGetBean(name, null, null, false); }doGetBean(name, null, null, false)
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {// 這里不直接name主要是因為alias和FactoryBean的原因// 1、別名需要轉(zhuǎn)換成真正的beanName// 2、如果傳入的name是實現(xiàn)了FactoryBean接口的話,那么傳入的name是以&開頭的,需要將首字母&移除final String beanName = transformedBeanName(name); // 獲取beanNameObject bean;// 這個方法在初始化的時候會調(diào)用,在getBean的時候也會調(diào)用,原因://// 嘗試從三級緩存中獲取bean實例//// Spring循環(huán)依賴的原理:// 在創(chuàng)建單例bean的時候會存在依賴注入的情況,為了避免循環(huán)依賴,Spring在創(chuàng)建bean的原則是不等bean創(chuàng)建完成就會將創(chuàng)建bean的ObjectFactory提早曝光,添加到singletonFactories中// 將ObjectFactory加入到緩存中,一旦下一個bean創(chuàng)建的時候需要依賴注入上個bean則直接從緩存中獲取ObjectFactoryObject sharedInstance = getSingleton(beanName); // 根據(jù)beanName嘗試從三級緩存中獲取bean實例// 當(dāng)三級緩存中存在此bean,表示當(dāng)前該bean已創(chuàng)建完成 || 正在創(chuàng)建if (sharedInstance != null && args == null) {if (logger.isDebugEnabled()) {// 該bean在singletonFactories,但是還未初始化,因為此bean存在循環(huán)依賴if (isSingletonCurrentlyInCreation(beanName)) {logger.debug("Returning eagerly caFFched instance of singleton bean '" + beanName +"' that is not fully initialized yet - a consequence of a circular reference");}else {logger.debug("Returning cached instance of singleton bean '" + beanName + "'");}}// 返回對應(yīng)的實例,有時候存在諸如BeanFactory的情況并不是直接返回實例本身而是返回指定方法返回的實例// 如果sharedInstance是普通的單例bean,下面的方法會直接返回,但如果sharedInstance是FactoryBean類型的,// 則需要調(diào)用getObject工廠方法獲取bean實例,如果用戶想獲取FactoryBean本身,這里也不會做特別的處理bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);}// 當(dāng)bean還未創(chuàng)建else {// Fail if we're already creating this bean instance:// We're assumably within a circular reference.// 如果該bean的scope是原型(phototype)不應(yīng)該在初始化的時候創(chuàng)建if (isPrototypeCurrentlyInCreation(beanName)) {throw new BeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.// 檢查當(dāng)前容器是否有父容器BeanFactory parentBeanFactory = getParentBeanFactory();// 如果父容器中存在此bean的實例,直接從父容器中獲取bean的實例并返回// 父子容器:Spring和SpringMVC都是一個容器,Spring容器是父容器,SpringMVC是子容器// controller的bean放在SpringMVC的子容器中,service、mapper放在Spring父容器中// 子容器可以訪問父容器中的bean實例,父容器不可以訪問子容器中的實例// controller中可以注入service的依賴,但是service不能注入controller的依賴if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {// Not found -> check parent.String nameToLookup = originalBeanName(name);if (parentBeanFactory instanceof AbstractBeanFactory) {return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);}else if (args != null) {// Delegation to parent with explicit args.return (T) parentBeanFactory.getBean(nameToLookup, args);}else {// No args -> delegate to standard getBean method.return parentBeanFactory.getBean(nameToLookup, requiredType);}}if (!typeCheckOnly) {// 添加到alreadyCreated set集合當(dāng)中,表示他已經(jīng)創(chuàng)建過了markBeanAsCreated(beanName);}try {// 從父容器中的BeanDefinitionMap和子容器中的BeanDefinitionMap合并的BeanDefinitionMap中獲取BeanDefinition對象final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.// 獲取當(dāng)前bean依賴注入的的屬性,bean的初始化之前里面依賴的屬性必須先初始化String[] dependsOn = mbd.getDependsOn();if (dependsOn != null) {for (String dep : dependsOn) {if (isDependent(beanName, dep)) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");}registerDependentBean(dep, beanName);try {getBean(dep);}catch (NoSuchBeanDefinitionException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"'" + beanName + "' depends on missing bean '" + dep + "'", ex);}}}// Create bean instance.// 正式開始創(chuàng)建bean實例if (mbd.isSingleton()) { // 當(dāng)該bean的scope為singleton或者為空時sharedInstance = getSingleton(beanName, () -> { // 從三級緩存中獲取bean實例try {return createBean(beanName, mbd, args); // 真正創(chuàng)建bean}catch (BeansException ex) {// Explicitly remove instance from singleton cache: It might have been put there// eagerly by the creation process, to allow for circular reference resolution.// Also remove any beans that received a temporary reference to the bean.destroySingleton(beanName);throw ex;}});bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}// 創(chuàng)建 prototype 類型的 bean 實例else if (mbd.isPrototype()) {// It's a prototype -> create a new instance.Object prototypeInstance = null;try {beforePrototypeCreation(beanName);prototypeInstance = createBean(beanName, mbd, args);}finally {afterPrototypeCreation(beanName);}bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}// 創(chuàng)建其他類型的bean實例else {String scopeName = mbd.getScope();final Scope scope = this.scopes.get(scopeName);if (scope == null) {throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");}try {Object scopedInstance = scope.get(beanName, () -> {beforePrototypeCreation(beanName);try {return createBean(beanName, mbd, args);}finally {afterPrototypeCreation(beanName);}});bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch (IllegalStateException ex) {throw new BeanCreationException(beanName,"Scope '" + scopeName + "' is not active for the current thread; consider " +"defining a scoped proxy for this bean if you intend to refer to it from a singleton",ex);}}}catch (BeansException ex) {cleanupAfterBeanCreationFailure(beanName);throw ex;}}// Check if required type matches the type of the actual bean instance.// 類型轉(zhuǎn)換if (requiredType != null && !requiredType.isInstance(bean)) {try {T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);if (convertedBean == null) {throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}return convertedBean;}catch (TypeMismatchException ex) {if (logger.isDebugEnabled()) {logger.debug("Failed to convert bean '" + name + "' to required type '" +ClassUtils.getQualifiedName(requiredType) + "'", ex);}throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}return (T) bean; }getSingleton(beanName)
@Override @Nullable public Object getSingleton(String beanName) {return getSingleton(beanName, true); }getSingleton(beanName, true)
@Nullable protected Object getSingleton(String beanName, boolean allowEarlyReference) { // allowEarlyReference表示是否允許從singletonFactories中通過getObject拿到對象// 嘗試從三級緩存中獲取bean實例Object singletonObject = this.singletonObjects.get(beanName); // 從一級緩存中獲取bean// 如果一級緩存中不存在該bean實例 && 該bean正在創(chuàng)建中if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { // isSingletonCurrentlyInCreation(beanName)判斷這個bean是否在創(chuàng)建過程中,對象是否有循環(huán)依賴synchronized (this.singletonObjects) {singletonObject = this.earlySingletonObjects.get(beanName); // 嘗試從二級緩存中獲取bean實例// 如果二級緩存中不存在giantbean實例 && 允許從singletonFactories從獲取bean實例if (singletonObject == null && allowEarlyReference) {ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); // 從三級緩存中獲取bean實例// 如果bean存在,將該bean實例從三級緩存升級到二級緩存中,并且從三級緩存中刪除if (singletonFactory != null) {singletonObject = singletonFactory.getObject();this.earlySingletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);}}}}return singletonObject; }createBean(beanName, mbd, args)
@Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {if (logger.isDebugEnabled()) {logger.debug("Creating instance of bean '" + beanName + "'");}RootBeanDefinition mbdToUse = 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.// 確認(rèn)bean真實加載進(jìn)行來了Class<?> resolvedClass = resolveBeanClass(mbd, beanName);if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {mbdToUse = new RootBeanDefinition(mbd);mbdToUse.setBeanClass(resolvedClass);}// Prepare method overrides.try {mbdToUse.prepareMethodOverrides();}catch (BeanDefinitionValidationException ex) {throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),beanName, "Validation of method overrides failed", ex);}try {// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.// 主要是來執(zhí)行實現(xiàn)了InstantiationAwareBeanPostProcessor接口的BeanPostProcesser,但是返回的bean始終為null// AOP核心方法,用來處理使用@Aspect注解標(biāo)識的bean,以便后面生成動態(tài)代理Object bean = resolveBeforeInstantiation(beanName, mbdToUse);// 生成的bean實例存在就返回if (bean != null) {return bean;}}catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,"BeanPostProcessor before instantiation of bean failed", ex);}try {// 實例化beanObject beanInstance = doCreateBean(beanName, mbdToUse, args);if (logger.isDebugEnabled()) {logger.debug("Finished creating instance of bean '" + beanName + "'");}return beanInstance;}catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {// A previously detected exception with proper bean creation context already,// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.throw ex;}catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);} }resolveBeforeInstantiation(beanName, mbdToUse)
@Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {Object bean = null;// 檢測是否被解析過if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {// Make sure bean class is actually resolved at this point.// hasInstantiationAwareBeanPostProcessors()是來判斷容器中是否有InstantiationAwareBeanPostProcessor的實現(xiàn)beanif (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {Class<?> targetType = determineTargetType(beanName, mbd); // 獲取bean的目標(biāo)類型if (targetType != null) {// 執(zhí)行實現(xiàn)了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的前置處理方法postProcessBeforeInstantiation方法bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);if (bean != null) {// 執(zhí)行實現(xiàn)了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的后置處理方法postProcessAfterInitialization方法bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);}}}mbd.beforeInstantiationResolved = (bean != null);}return bean; }applyBeanPostProcessorsBeforeInstantiation(targetType, beanName)
@Nullable protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);if (result != null) {return result;}}}return null; }applyBeanPostProcessorsAfterInitialization(bean, beanName)
@Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)throws BeansException {Object result = existingBean;for (BeanPostProcessor processor : getBeanPostProcessors()) {Object current = processor.postProcessAfterInitialization(result, beanName);if (current == null) {return result;}result = current;}return result; }doCreateBean(beanName, mbdToUse, args)
/*** 初始化bean實例(解決循環(huán)依賴問題)*/ protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {// 調(diào)用bean的構(gòu)造方法進(jìn)行初始化,經(jīng)過這一步,bean屬性并沒有被賦值,只是一個空殼,這是bean初始化的【早期對象】instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}// 創(chuàng)建bean實例轉(zhuǎn)化成BeanWrapper對象if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}final Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {// 處理bean中實現(xiàn)了MergedBeanDefinitionPostProcessor后置處理器的類中的postProcessMergedBeanDefinition方法applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.// 判斷bean是否存在循環(huán)依賴// 如果當(dāng)前bean是單例,且支持循環(huán)依賴,且當(dāng)前bean正在創(chuàng)建,通過往singletonFactories添加一個objectFactory,這樣后期如果有其他bean依賴該bean 可以從singletonFactories獲取到beanboolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isDebugEnabled()) {logger.debug("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}// 解決Spring循環(huán)依賴問題// 添加工廠對象到singletonFactories緩存中【提前暴露早期對象】addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.// 初始化bean實例Object exposedObject = bean;try {// 給已經(jīng)已經(jīng)初始化的屬性賦值,包括完成bean的依賴注入populateBean(beanName, mbd, instanceWrapper);// 初始化bean實例exposedObject = initializeBean(beanName, exposedObject, mbd);}catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;}else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);}}// 解決循環(huán)依賴if (earlySingletonExposure) {Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {if (exposedObject == bean) {exposedObject = earlySingletonReference;}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);for (String dependentBean : dependentBeans) {if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {actualDependentBeans.add(dependentBean);}}if (!actualDependentBeans.isEmpty()) {throw new BeanCurrentlyInCreationException(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.");}}}}// Register bean as disposable.// 銷毀try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject; }applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof MergedBeanDefinitionPostProcessor) {MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);}} }bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName)
 MergedBeanDefinitionPostProcessor的實現(xiàn)類可以用來處理@Autowired、@Value、@PostConstruct、@PreDestroy、@Scheduled等Spring提供的注解
下面以實現(xiàn)類AutowiredAnnotationBeanPostProcessor用來處理@Autowired、@Value注解舉例
當(dāng)bdp的實現(xiàn)類是AutowiredAnnotationBeanPostProcessor時,將調(diào)用AutowiredAnnotationBeanPostProcessor重寫的postProcessMergedBeanDefinition方法
@Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);metadata.checkConfigMembers(beanDefinition); }findAutowiringMetadata(beanName, beanType, null)
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {// Fall back to class name as cache key, for backwards compatibility with custom callers.String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());// Quick check on the concurrent map first, with minimal locking.InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);if (InjectionMetadata.needsRefresh(metadata, clazz)) {synchronized (this.injectionMetadataCache) {metadata = this.injectionMetadataCache.get(cacheKey);if (InjectionMetadata.needsRefresh(metadata, clazz)) {if (metadata != null) {metadata.clear(pvs);}// 解析等待依賴注入類的所有屬性,構(gòu)建InjectionMetadata對象,它是通過分析類中所有屬性和所有方法中是否有該注解metadata = buildAutowiringMetadata(clazz);this.injectionMetadataCache.put(cacheKey, metadata);}}}return metadata; }buildAutowiringMetadata(clazz)
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();Class<?> targetClass = clazz;do {final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();// 掃描所有屬性ReflectionUtils.doWithLocalFields(targetClass, field -> {// 通過分析屬于一個字段的所有注解來查找@Autowired注解AnnotationAttributes ann = findAutowiredAnnotation(field);if (ann != null) {if (Modifier.isStatic(field.getModifiers())) {if (logger.isWarnEnabled()) {logger.warn("Autowired annotation is not supported on static fields: " + field);}return;}boolean required = determineRequiredStatus(ann);currElements.add(new AutowiredFieldElement(field, required));}});// 掃描所有方法ReflectionUtils.doWithLocalMethods(targetClass, method -> {Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {return;}// 通過分析屬于一個方法的所有注解來查找@Autowired注解AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {if (Modifier.isStatic(method.getModifiers())) {if (logger.isWarnEnabled()) {logger.warn("Autowired annotation is not supported on static methods: " + method);}return;}if (method.getParameterCount() == 0) {if (logger.isWarnEnabled()) {logger.warn("Autowired annotation should only be used on methods with parameters: " +method);}}boolean required = determineRequiredStatus(ann);PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);currElements.add(new AutowiredMethodElement(method, required, pd));}});elements.addAll(0, currElements);targetClass = targetClass.getSuperclass();}while (targetClass != null && targetClass != Object.class);return new InjectionMetadata(clazz, elements); }populateBean(beanName, mbd, instanceWrapper)
/*** 給已經(jīng)已經(jīng)初始化的屬性賦值,包括完成bean的依賴注入* 這個方法最重要就是最后一個方法applyPropertyValues(beanName, mbd, bw, pvs):為屬性賦值*/ protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {// 這一大段代碼省略......// 為屬性賦值if (pvs != null) {applyPropertyValues(beanName, mbd, bw, pvs);} }applyPropertyValues(beanName, mbd, bw, pvs)
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {// 這一大段代碼省略......// 為當(dāng)前bean中屬性賦值,包括依賴注入的屬性O(shè)bject resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);// 這一大段代碼省略...... }valueResolver.resolveValueIfNecessary(pv, originalValue)
/*** 如果當(dāng)前初始化的bean有屬性需要注入的,將會調(diào)用resolveReference(argName, ref)來返回需要注入的bean*/ public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {// 獲取需要依賴注入屬性的值if (value instanceof RuntimeBeanReference) {RuntimeBeanReference ref = (RuntimeBeanReference) value;return resolveReference(argName, ref);}// 這一大段代碼省略...... }resolveReference(argName, ref)
private Object resolveReference(Object argName, RuntimeBeanReference ref) {try {Object bean;String refName = ref.getBeanName();refName = String.valueOf(doEvaluate(refName));if (ref.isToParent()) {if (this.beanFactory.getParentBeanFactory() == null) {throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,"Can't resolve reference to bean '" + refName +"' in parent factory: no parent factory available");}bean = this.beanFactory.getParentBeanFactory().getBean(refName);}else {// 當(dāng)前初始化bean主要為屬性注入另外一個bean,調(diào)用getBean()方法獲取需要注入的bean,最終注入到屬性中bean = this.beanFactory.getBean(refName);this.beanFactory.registerDependentBean(refName, this.beanName);}if (bean instanceof NullBean) {bean = null;}return bean;}catch (BeansException ex) {throw new BeanCreationException(this.beanDefinition.getResourceDescription(), this.beanName,"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);} }getSingleton(beanName, singletonFactory)
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {Assert.notNull(beanName, "Bean name must not be null");synchronized (this.singletonObjects) {// 嘗試從一級緩存中獲取bean實例Object singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null) {if (this.singletonsCurrentlyInDestruction) {throw new BeanCreationNotAllowedException(beanName,"Singleton bean creation not allowed while singletons of this factory are in destruction " +"(Do not request a bean from a BeanFactory in a destroy method implementation!)");}if (logger.isDebugEnabled()) {logger.debug("Creating shared instance of singleton bean '" + beanName + "'");}// 將beanName添加到singletonsCurrentlyInCreation集合中,// 用于表明beanName對應(yīng)的bean正在創(chuàng)建中beforeSingletonCreation(beanName);boolean newSingleton = false;boolean recordSuppressedExceptions = (this.suppressedExceptions == null);if (recordSuppressedExceptions) {this.suppressedExceptions = new LinkedHashSet<>();}try {// 調(diào)用FactoryBean接口中的getObject()方法獲取bean實例singletonObject = singletonFactory.getObject();newSingleton = true;}catch (IllegalStateException ex) {// Has the singleton object implicitly appeared in the meantime ->// if yes, proceed with it since the exception indicates that state.singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null) {throw ex;}}catch (BeanCreationException ex) {if (recordSuppressedExceptions) {for (Exception suppressedException : this.suppressedExceptions) {ex.addRelatedCause(suppressedException);}}throw ex;}finally {if (recordSuppressedExceptions) {this.suppressedExceptions = null;}// 從singletonsCurrentlyInCreation實現(xiàn)FactoryBean接口中的bean,表明實現(xiàn)了FactoryBean接口的bean獲取完畢afterSingletonCreation(beanName);}if (newSingleton) {// 最后將singletonObject添加到singletonObjects一級緩存中,同時將二級、三級緩存中的bean刪除addSingleton(beanName, singletonObject);}}return singletonObject;} }addSingleton(beanName, singletonObject)
/*** 將singletonObject添加到singletonObjects一級緩存中,同時將二級、三級緩存中的bean刪除*/ protected void addSingleton(String beanName, Object singletonObject) {synchronized (this.singletonObjects) {this.singletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName);this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);} }?
總結(jié)
以上是生活随笔為你收集整理的AnnotationConfigApplicationContext容器初始化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 模拟springIOC容器的annota
- 下一篇: Spring系列之BeanPostPro
