ConfigurationClassPostProcessor—Spring中最最最重要的后置處理器!沒有之一!!!
1.結構
ConfigurationClassPostProcessor 實現了 BeanDefinitionRegistryPostProcessor 接口,而 BeanDefinitionRegistryPostProcessor 接口又繼承了BeanFactoryPostProcessor 接口。
// BeanDefinitionRegistryPostProcessor 接口實現 @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { int registryId = System.identityHashCode(registry); if (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); } // BeanFactoryPostProcessor 接口實現 @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { int factoryId = System.identityHashCode(beanFactory); if (this.factoriesPostProcessed.contains(factoryId)) { throw new IllegalStateException( "postProcessBeanFactory already called on this post-processor against " + beanFactory); } this.factoriesPostProcessed.add(factoryId); if (!this.registriesPostProcessed.contains(factoryId)) { // Simply call processConfigurationClasses lazily at this point then. processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory); } //對加了@Configuration注解的配置類進行Cglib代理 enhanceConfigurationClasses(beanFactory); beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory)); }
2.注冊時機
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; ...省略 // 創建容器上下文,執行Spring框架中的this(); context = createApplicationContext(); ...省略 return context; }
// 這里的DEFAULT_SERVLET_WEB_CONTEXT_CLASS是org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { switch (this.webApplicationType) { case SERVLET: contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS); break; case REACTIVE: contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS); break; default: contextClass = Class.forName(DEFAULT_CONTEXT_CLASS); } } ... } // 實例化 AnnotationConfigServletWebServerApplicationContext return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }
public AnnotationConfigApplicationContext() { //初始化讀取注解的Bean定義讀取器,並注冊注解配置的的處理器 this.reader = new AnnotatedBeanDefinitionReader(this); //初始化一個ClassPath類型的Bean的掃描器 this.scanner = new ClassPathBeanDefinitionScanner(this); }
// 在構造 AnnotatedBeanDefinitionReader時調用下面方法 注冊下面五個內置處理器 AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
//五個內置處理器 ConfigurationClassPostProcessor = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor" implements BeanDefinitionRegistryPostProcessor,PriorityOrdered AutowiredAnnotationBeanPostProcessor = "org.springframework.context.annotation.internalAutowiredAnnotationProcessor" implements BeanPostProcessor,PriorityOrdered CommonAnnotationBeanPostProcessor = "org.springframework.context.annotation.internalCommonAnnotationProcessor" implements BeanPostProcessor EventListenerMethodProcessor = "org.springframework.context.event.internalEventListenerProcessor" implements BeanFactoryPostProcessor DefaultEventListenerFactory = "org.springframework.context.event.internalEventListenerFactory"
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) { DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet(8); RootBeanDefinition def; //用來解析加了@Configuration的配置類,還會解析@ComponentScan、@ComponentScans注解掃描的包,以及解析@Import等注解。 if (!registry.containsBeanDefinition("org.springframework.context.annotation.internalConfigurationAnnotationProcessor")) { def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalConfigurationAnnotationProcessor")); } //用來解析@Autowired和@Value、@Inject注解 if (!registry.containsBeanDefinition("org.springframework.context.annotation.internalAutowiredAnnotationProcessor")) { def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalAutowiredAnnotationProcessor")); } //用來處理@PostConstruct、@PreDestroy和@Resource注解 if (jsr250Present && !registry.containsBeanDefinition("org.springframework.context.annotation.internalCommonAnnotationProcessor")) { def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalCommonAnnotationProcessor")); } if (jpaPresent && !registry.containsBeanDefinition("org.springframework.context.annotation.internalPersistenceAnnotationProcessor")) { def = new RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor", AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException var6) { throw new IllegalStateException("Cannot load optional framework class: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor", var6); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.annotation.internalPersistenceAnnotationProcessor")); } //用來處理@EventListener事件監聽注解 if (!registry.containsBeanDefinition("org.springframework.context.event.internalEventListenerProcessor")) { def = new RootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.event.internalEventListenerProcessor")); } //注冊事件監聽器工廠 if (!registry.containsBeanDefinition("org.springframework.context.event.internalEventListenerFactory")) { def = new RootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, "org.springframework.context.event.internalEventListenerFactory")); } return beanDefs; }
3.觸發時機
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); configureHeadlessProperty(); SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); ...省略 // 刷新容器,注冊bean refreshContext(context); ...省略 return context; }
AbstractApplicationContext下: public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 准備刷新上下文 prepareRefresh(); // 刷新內部bean工廠 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 准備BeanFactory prepareBeanFactory(beanFactory); try { // 處理后置處理器,目前沒有任何實現 postProcessBeanFactory(beanFactory); /* 拿到所有自定義和內置的BeanDefinitionRegistryPostProcessor后置處理器,循環調用postProcessBeanDefinitionRegistry; 其中最重要的是ConfigurationClassPostProcessor處理器的執行:遍歷BeanDefinition找到帶有@Configuration注解的BeanDefinition, 解析處理配置類中的@Import,@PropertySources,@ComponentScans(如果存在注解,則會掃描對應路徑的類轉換成BeanDefinition, 存入BeanDefinitionMap),@Bean(同樣)注解等 */ invokeBeanFactoryPostProcessors(beanFactory); // 注冊BeanPostProcessor后置處理器 registerBeanPostProcessors(beanFactory); // 初始化消息資源解析器 initMessageSource(); // 初始化注冊一個單列ApplicationContext事件監聽器applicationEventMulticaster initApplicationEventMulticaster(); // 初始化特定上下文子類中的其他特殊bean。交給子類實現 onRefresh(); //注冊事件監聽器,派發容器初始化的事件:監聽器需要實現ApplicationListener接口 registerListeners(); // 實例所有的單例Bean,創建單例非懶加載的bean finishBeanFactoryInitialization(beanFactory); // 容器初始化完成,發布事件 finishRefresh(); } catch (BeansException ex) { // 銷毀已經創建的單實例以避免懸空資源。 destroyBeans(); // 重置 'active' 標記 cancelRefresh(ex); throw ex; } finally { // 重置Spring核心的緩存 resetCommonCaches(); } } }
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { // 獲取容器中的Bean工廠后置處理器(注意這里Bean工廠后置處理器還沒有初始化) // getBeanFactoryPostProcessors()方法一般是獲取不到值的,除非我們手動調用addBeanFactoryPostProcessor方法或注解@Component來注入BeanFactoryPostProcessors對象 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors()); }
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { Set<String> processedBeans = new HashSet<>(); //開始處理BeanDefinitionRegistryPostProcessor // 判斷beanFactory是否為BeanDefinitionRegistry,beanFactory為DefaultListableBeanFactory,而DefaultListableBeanFactory實現了BeanDefinitionRegistry接口,因此為true if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; // 用於存放普通的BeanFactoryPostProcessor List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); // 用於存放BeanDefinitionRegistryPostProcessor List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); // 首先處理入參中的beanFactoryPostProcessors,遍歷區分BeanDefinitionRegistryPostProcessor和普通BeanFactoryPostProcessor for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; // 執行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法 registryProcessor.postProcessBeanDefinitionRegistry(registry); // 添加到registryProcessors(用於最后執行postProcessBeanFactory方法) registryProcessors.add(registryProcessor); }else { // 添加到regularPostProcessors(用於最后執行postProcessBeanFactory方法) regularPostProcessors.add(postProcessor); } } // 首先,調用實現PriorityOrdered的BeanDefinitionRegistryPostProcessors // 用於保存本次要執行的BeanDefinitionRegistryPostProcessor。 List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // 找出所有實現BeanDefinitionRegistryPostProcessor接口的Bean的beanName String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 校驗是否實現了PriorityOrdered接口 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } // 進行排序(根據是否實現PriorityOrdered、Ordered接口和order值來排序) sortPostProcessors(currentRegistryProcessors, beanFactory); // 合並 registryProcessors.addAll(currentRegistryProcessors); // 遍歷currentRegistryProcessors, 執行postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); // 清空currentRegistryProcessors currentRegistryProcessors.clear(); // 然后調用實現Ordered的BeanDefinitionRegistryPostProcessors。 // 找出所有實現BeanDefinitionRegistryPostProcessor接口的Bean的beanName postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 校驗是否實現了Ordered接口,並且還未執行過 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(); // 最后,調用所有其他BeanDefinitionRegistryPostProcessor,直到沒有其他的出現。 boolean reiterate = true; while (reiterate) { reiterate = false; // 找出所有實現BeanDefinitionRegistryPostProcessor接口的類 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(); } // 調用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor繼承自BeanFactoryPostProcessor) invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); // 調用所有普通BeanFactoryPostProcessor的postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); }else { // 調用在上下文實例中注冊的工廠處理器。 invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } // 到這里,容器中的所有BeanDefinitionRegistryPostProcessor已經全部處理完畢. ...省略 // 清除元數據緩存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType) // 因為后處理器可能已經修改了原始元數據,例如, 替換值中的占位符... beanFactory.clearMetadataCache(); }
4.作用
postProcessBeanDefinitionRegistry;
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { ...省略 // BeanDefinitionRegistryPostProcessor接口方法 processConfigBeanDefinitions(registry); }
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) { List<BeanDefinitionHolder> configCandidates = new ArrayList<>(); String[] candidateNames = registry.getBeanDefinitionNames(); for (String beanName : candidateNames) { BeanDefinition beanDef = registry.getBeanDefinition(beanName); if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) { if (logger.isDebugEnabled()) { logger.debug("Bean definition has already been processed as a configuration class: " + beanDef); } } // ① 判斷是否為配置類 // 如果配置類包含@Bean,@Component,@ComponentScan,@Import,@ImportResource注解,則設置配置類屬性為lite // 如果配置類加了@Configuration,則設置配置類屬性為full else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) { configCandidates.add(new BeanDefinitionHolder(beanDef, beanName)); } } if (configCandidates.isEmpty()) { return; } // order排序 configCandidates.sort((bd1, bd2) -> { int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition()); int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition()); return Integer.compare(i1, i2); }); // beanName的生成器 SingletonBeanRegistry sbr = null; if (registry instanceof SingletonBeanRegistry) { sbr = (SingletonBeanRegistry) registry; if (!this.localBeanNameGeneratorSet) { BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton( AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR); if (generator != null) { this.componentScanBeanNameGenerator = generator; this.importBeanNameGenerator = generator; } } } if (this.environment == null) { this.environment = new StandardEnvironment(); } // 循環解析配置類 ConfigurationClassParser parser = new ConfigurationClassParser( this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry); Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates); Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size()); do { // ② 解析配置類 parser.parse(candidates); parser.validate(); Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses()); configClasses.removeAll(alreadyParsed); if (this.reader == null) { this.reader = new ConfigurationClassBeanDefinitionReader( registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry()); } // ③ 將解析的配置類轉成BeanDefinition加入BeanDefinitionMap中 // 掃描上面解析的配置類中的@Import、@Bean、 this.reader.loadBeanDefinitions(configClasses); alreadyParsed.addAll(configClasses); candidates.clear(); // 判斷有沒有添加新的BeanDefinition 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()); } // 如果有未解析的類,則將其添加到candidates中,這樣candidates不為空,就會進入到下一次的while的循環中 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()); // 將ImportRegistry注冊為bean以支持importware @Configuration類 if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) { sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry()); } if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { // 清空緩存 ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); } }
① 判斷是否為配置類:ConfigurationClassUtils.checkConfigurationClassCandidate();
public static boolean checkConfigurationClassCandidate( BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) { ...省略 Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName()); // @Configuration 的屬性 proxyBeanMethods默認為true,表示cglib會為@Configuration生成一個代理類,在同一個配置文件中獲取被@Bean注解標注的對象時會直接從IOC容器之中獲取; // 設置 BeanDefinition 的 configurationClass 屬性值為full if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) { beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL); } // 如果類上包含@Component、@ComponentScan、@Import、@ImportResource、@Bean注解任意一個 // 設置 BeanDefinition 的 configurationClass 屬性值為lite else if (config != null || isConfigurationCandidate(metadata)) { beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE); } else { return false; } ... return true; }
② 解析配置類:parser.parse(); (ConfigurationClassParser.parse())
public void parse(Set<BeanDefinitionHolder> configCandidates) { for (BeanDefinitionHolder holder : configCandidates) { BeanDefinition bd = holder.getBeanDefinition(); try { // 如果bean實現自 AnnotatedBeanDefinition 接口,則進行注解bean定義的解析 if (bd instanceof AnnotatedBeanDefinition) { parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName()); } // 如果bean實現自 AbstractBeanDefinition 接口,則進行抽象bean定義的解析 else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) { parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName()); } else { // 常規配置類進行解析 parse(bd.getBeanClassName(), holder.getBeanName()); } } ... } // 加載解析spring.properties中的配置類 this.deferredImportSelectorHandler.process(); }
protected final void parse(Class<?> clazz, String beanName) throws IOException { processConfigurationClass(new ConfigurationClass(clazz, beanName), DEFAULT_EXCLUSION_FILTER); } protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException { ...判斷是否已經解析過 ...省略 // 獲取源類 SourceClass sourceClass = asSourceClass(configClass, filter); do { // 遞歸地處理配置類及其超類,返回值是configClass 的父類 sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter); } while (sourceClass != null); // 記錄已經解析的配置類 this.configurationClasses.put(configClass, configClass); }
@Nullable protected final SourceClass doProcessConfigurationClass( ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter) throws IOException { if (configClass.getMetadata().isAnnotated(Component.class.getName())) { // 遞歸處理內部類 processMemberClasses(configClass, sourceClass, filter); } // 處理 @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.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() + "]. Reason: Environment must implement ConfigurableEnvironment"); } } // 處理所有 @ComponentScan 注解 Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable( sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class); if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) { for (AnnotationAttributes componentScan : componentScans) { // 執行掃描 @ComponentScan 指定路徑下所有 @Component // Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName()); // 檢查 ComponentScan 掃描得到的 BeanDefinition 定義,循環解析 for (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()); } } } } // 處理所有 @Import 注解,將 import 的bean變為 ConfigurationClass processImports(configClass, sourceClass, getImports(sourceClass), filter, true); // 處理所有 @ImportResource 注解 AnnotationAttributes 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); } } // 處理單個 @Bean 方法 Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass); for (MethodMetadata methodMetadata : beanMethods) { configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass)); } // 處理接口默認方法 processInterfaces(configClass, sourceClass); // 如果有父類,處理父類 if (sourceClass.getMetadata().hasSuperClass()) { String superclass = sourceClass.getMetadata().getSuperClassName(); if (superclass != null && !superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) { this.knownSuperclasses.put(superclass, configClass); // 找到父類,返回 return sourceClass.getSuperClass(); } } return null; }
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass, Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter, boolean checkForCircularImports) { // 如果類上沒有@Import 注解,直接返回 if (importCandidates.isEmpty()) { return; } // 依賴檢查 if (checkForCircularImports && isChainedImportOnStack(configClass)) { this.problemReporter.error(new CircularImportProblem(configClass, this.importStack)); } else { this.importStack.push(configClass); try { // 處理所有 @Import ,@Import存在三種情況 // ①:@Import的類實現了 ImportSelector 接口,實例化並執行 selectImports 方法 // ②:@Import的類實現了 DeferredImportSelector接口,實例化並延遲處理 // ③:@Import的類實現了 ImportBeanDefinitionRegistrar接口,實例化並加入 ImportBeanDefinitionRegistrars中后續處理 for (SourceClass candidate : importCandidates) { if (candidate.isAssignable(ImportSelector.class)) { Class<?> candidateClass = candidate.loadClass(); // 實例化 ImportSelector ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class, this.environment, this.resourceLoader, this.registry); Predicate<String> selectorFilter = selector.getExclusionFilter(); if (selectorFilter != null) { exclusionFilter = exclusionFilter.or(selectorFilter); } // 如果是實現 DeferredImportSelector ,則延遲處理 if (selector instanceof DeferredImportSelector) { this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector); } else { // 如果不是實現 DeferredImportSelector, 則執行 selectImports方法 String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata()); Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter); // 遞歸繼續處理, 被Import進來的類可能也有@Import注解 processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false); } } // 如果是實現 ImportBeanDefinitionRegistrar接口 else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) { Class<?> candidateClass = candidate.loadClass(); // 實例化 ImportBeanDefinitionRegistrar ImportBeanDefinitionRegistrar registrar = ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class, this.environment, this.resourceLoader, this.registry); // 加入 importBeanDefinitionRegistrars 中,后續處理configClass 時一並處理 configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata()); } else { // Import 普通類,則將其當作帶有@Configuration的類一樣處理 this.importStack.registerImport( currentSourceClass.getMetadata(), candidate.getMetadata().getClassName()); processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter); } } } catch (BeanDefinitionStoreException ex) { throw ex; } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to process import candidates for configuration class [" + configClass.getMetadata().getClassName() + "]", ex); } finally { this.importStack.pop(); } } }
這里 Import 的類 由於實現了 DeferredImportSelector, 所以延遲處理 @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {...} public class AutoConfigurationImportSelector implements DeferredImportSelector{...}
this.deferredImportSelectorHandler.process();
此處最重要的就是加載 spring.factories中的configuration 類
public void process() { List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors; this.deferredImportSelectors = null; try { if (deferredImports != null) { DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler(); deferredImports.sort(DEFERRED_IMPORT_COMPARATOR); deferredImports.forEach(handler::register); handler.processGroupImports(); } } finally { this.deferredImportSelectors = new ArrayList<>(); } } // ConfigurationClassParser 下內部類 DeferredImportSelectorGroupingHandler : public void processGroupImports() { for (DeferredImportSelectorGrouping grouping : this.groupings.values()) { Predicate<String> exclusionFilter = grouping.getCandidateFilter(); grouping.getImports().forEach(entry -> { ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata()); try { // 遞歸繼續處理, 被Import進來的類可能也有@Import注解 processImports(configurationClass, asSourceClass(configurationClass, exclusionFilter), Collections.singleton(asSourceClass(entry.getImportClassName(), exclusionFilter)), exclusionFilter, false); } catch (BeanDefinitionStoreException ex) { throw ex; } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to process import candidates for configuration class [" + configurationClass.getMetadata().getClassName() + "]", ex); } }); } } // ConfigurationClassParser 下靜態內部類 DeferredImportSelectorGrouping public Iterable<Group.Entry> getImports() { for (DeferredImportSelectorHolder deferredImport : this.deferredImports) { this.group.process(deferredImport.getConfigurationClass().getMetadata(), deferredImport.getImportSelector()); } return this.group.selectImports(); } // AutoConfigurationImportSelector 下靜態內部類 AutoConfigurationGroup public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) { Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) .getAutoConfigurationEntry(annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); for (String importClassName : autoConfigurationEntry.getConfigurations()) { this.entries.putIfAbsent(importClassName, annotationMetadata); } } // AutoConfigurationImportSelector類下: protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } AnnotationAttributes attributes = getAttributes(annotationMetadata); List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); configurations = removeDuplicates(configurations); Set<String> exclusions = getExclusions(annotationMetadata, attributes); checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = getConfigurationClassFilter().filter(configurations); fireAutoConfigurationImportEvents(configurations, exclusions); return new AutoConfigurationEntry(configurations, exclusions); } protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }
③this.reader.loadBeanDefinitions(configClasses);
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) { TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator(); for (ConfigurationClass configClass : configurationModel) { // 遍歷加載配置文件的 BeanDefinition 到BeanDefinitionMap loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator); } } private void loadBeanDefinitionsForConfigurationClass( ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) { ...省略 if (configClass.isImported()) { // 處理通過 @Import 方式導入的配置類 registerBeanDefinitionForImportedConfigurationClass(configClass); } // 遍歷處理配置類中 @Bean注解 的方法 for (BeanMethod beanMethod : configClass.getBeanMethods()) { loadBeanDefinitionsForBeanMethod(beanMethod); } // 處理通過 @ImportResource 方式導入的 XML配置類,(不詳述) loadBeanDefinitionsFromImportedResources(configClass.getImportedResources()); // 處理實現 ImportBeanDefinitionRegistrar接口的配置類, 執行registerBeanDefinitions方法 loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars()); } private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) { AnnotationMetadata metadata = configClass.getMetadata(); AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata); ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef); configBeanDef.setScope(scopeMetadata.getScopeName()); // 生成 BeanName String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry); // 處理 @Lazy、@Primary、@DependsOn、@Role、@Description 屬性 AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName); // 設置 作用域 definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 添加到 BeanDefinitionMap 中 this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition()); configClass.setBeanName(configBeanName); ... } private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) { ConfigurationClass configClass = beanMethod.getConfigurationClass(); MethodMetadata metadata = beanMethod.getMetadata(); String methodName = metadata.getMethodName(); ...省略 AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class); Assert.state(bean != null, "No @Bean annotation attributes"); // Consider name and any aliases List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name"))); String beanName = (!names.isEmpty() ? names.remove(0) : methodName); // 注冊別名 for (String alias : names) { this.registry.registerAlias(beanName, alias); } // 判斷當前 Bean 是否已經存在 if (isOverriddenByExistingDefinition(beanMethod, beanName)) { if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) { throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(), beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() + "' clashes with bean name for containing configuration class; please make those names unique!"); } return; } ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata, beanName); beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource())); // 處理靜態 Bean if (metadata.isStatic()) { if (configClass.getMetadata() instanceof StandardAnnotationMetadata) { beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass()); } else { beanDef.setBeanClassName(configClass.getMetadata().getClassName()); } beanDef.setUniqueFactoryMethodName(methodName); } else { // 實例 @Bean 方法 beanDef.setFactoryBeanName(configClass.getBeanName()); beanDef.setUniqueFactoryMethodName(methodName); } // 設置解析工廠方法 if (metadata instanceof StandardMethodMetadata) { beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod()); } beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor. SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE); // 處理 @Lazy、@Primary、@DependsOn、@Role、@Description 屬性 AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata); Autowire autowire = bean.getEnum("autowire"); if (autowire.isAutowire()) { beanDef.setAutowireMode(autowire.value()); } boolean autowireCandidate = bean.getBoolean("autowireCandidate"); if (!autowireCandidate) { beanDef.setAutowireCandidate(false); } // 處理初始方法 String initMethodName = bean.getString("initMethod"); if (StringUtils.hasText(initMethodName)) { beanDef.setInitMethodName(initMethodName); } // 處理銷毀方法 String destroyMethodName = bean.getString("destroyMethod"); beanDef.setDestroyMethodName(destroyMethodName); // 處理作用域 ScopedProxyMode proxyMode = ScopedProxyMode.NO; AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class); if (attributes != null) { beanDef.setScope(attributes.getString("value")); proxyMode = attributes.getEnum("proxyMode"); if (proxyMode == ScopedProxyMode.DEFAULT) { proxyMode = ScopedProxyMode.NO; } } // 如果有必要,替換原有的BeanDefinition BeanDefinition beanDefToRegister = beanDef; if (proxyMode != ScopedProxyMode.NO) { BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy( new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS); beanDefToRegister = new ConfigurationClassBeanDefinition( (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata, beanName); } // 注冊到 BeanDefinitionMap 中 this.registry.registerBeanDefinition(beanName, beanDefToRegister); } private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) { // 遍歷所有的實現 ImportBeanDefinitionRegistrar接口的配置類 registrars.forEach((registrar, metadata) -> // 執行registerBeanDefinitions方法 registrar.registerBeanDefinitions(metadata, this.registry, this.importBeanNameGenerator)); }
postProcessBeanFactory;
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { int factoryId = System.identityHashCode(beanFactory); if (this.factoriesPostProcessed.contains(factoryId)) { throw new IllegalStateException( "postProcessBeanFactory already called on this post-processor against " + beanFactory); } this.factoriesPostProcessed.add(factoryId); // 因為ConfigurationClassPostProcessor 實現 BeanDefinitionRegistryPostProcessor // 所以會先執行 postProcessBeanDefinitionRegistry, 而 postProcessBeanDefinitionRegistry 中又會執行 processConfigBeanDefinitions // 所以此處為避免重復執行,不會執行 if (!this.registriesPostProcessed.contains(factoryId)) { processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory); } // 對加了@Configuration注解的配置類進行Cglib代理 enhanceConfigurationClasses(beanFactory); // 添加 BeanPostProcessor 后置處理器:給 代理類添加 BeanFactory 屬性 beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory)); }
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) { ...省略 ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer(); for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) { ...省略 // 創建 代理類 Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader); ...省略 } } public Class<?> enhance(Class<?> configClass, @Nullable ClassLoader classLoader) { ...省略 // 核心代碼為 newEnHancer() Class<?> enhancedClass = createClass(newEnhancer(configClass, classLoader)); ...省略 return enhancedClass; } private Enhancer newEnhancer(Class<?> configSuperClass, @Nullable ClassLoader classLoader) { Enhancer enhancer = new Enhancer(); // CGLIB的動態代理基於繼承 enhancer.setSuperclass(configSuperClass); // 為新創建的代理對象設置一個父接口 enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class}); enhancer.setUseFactory(false); enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader)); // 添加回調方法, 每次代理對象的方法被調用時,都會先經過MethodInterceptor中的方法 enhancer.setCallbackFilter(CALLBACK_FILTER); enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes()); return enhancer; }