您的位置:首页 > 教育 > 培训 > 15、Spring~容器启动过程

15、Spring~容器启动过程

2024/7/6 0:08:14 来源:https://blog.csdn.net/sproutBoy/article/details/139842999  浏览:    关键词:15、Spring~容器启动过程

15、Spring~容器启动过程

  • 容器启动过程
    • AnnotationConfigApplicationContext类的四个构造器:
    • 启动过程详解
      • 无参构造方法
      • refresh()方法
      • prepareRefresh()方法
      • prepareBeanFactory()方法
      • invokeBeanFactoryPostProcessors()方法
      • registerBeanPostProcessors()方法
      • finishBeanFactoryInitialization()方法
    • GenericApplicationContext对象详解
      • 构造方法
    • DefaultListableBeanFactory对象详解
      • 构造方法
      • preInstantiateSingletons()方法
    • AnnotatedBeanDefinitionReader对象详解
      • 构造方法
    • ConditionEvaluator对象
      • 构造方法
    • AnnotationConfigUtils对象
      • registerAnnotationConfigProcessors()方法
      • unwrapDefaultListableBeanFactory()方法
    • ClassPathBeanDefinitionScanner对象
      • 构造方法
      • registerDefaultFilters()方法
    • PostProcessorRegistrationDelegate对象
      • invokeBeanFactoryPostProcessors()方法
      • registerBeanPostProcessors()方法
    • ConfigurationClassPostProcessor 对象
      • postProcessBeanDefinitionRegistry()方法

容器启动过程

  Spring容器的启动过程,其实就是看AnnotationConfigApplicationContext对象或ClassPathXmlApplicationContext对象的创建过程,xml配置文件的使用方式不多,我们重点解析配置类的启动方式,废话不多说,上代码,我们首先分析AnnotationConfigApplicationContext类的源码

package org.springframework.context.annotation;import java.util.Arrays;
import java.util.function.Supplier;import org.springframework.beans.factory.config.BeanDefinitionCustomizer;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.metrics.StartupStep;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;/*** Standalone application context, accepting <em>component classes</em> as input &mdash;* in particular {@link Configuration @Configuration}-annotated classes, but also plain* {@link org.springframework.stereotype.Component @Component} types and JSR-330 compliant* classes using {@code javax.inject} annotations.** <p>Allows for registering classes one by one using {@link #register(Class...)}* as well as for classpath scanning using {@link #scan(String...)}.** <p>In case of multiple {@code @Configuration} classes, {@link Bean @Bean} methods* defined in later classes will override those defined in earlier classes. This can* be leveraged to deliberately override certain bean definitions via an extra* {@code @Configuration} class.** <p>See {@link Configuration @Configuration}'s javadoc for usage examples.** @author Juergen Hoeller* @author Chris Beams* @see #register* @see #scan* @see AnnotatedBeanDefinitionReader* @see ClassPathBeanDefinitionScanner* @see org.springframework.context.support.GenericXmlApplicationContext* @since 3.0*/
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {private final AnnotatedBeanDefinitionReader reader;private final ClassPathBeanDefinitionScanner scanner;/*** Create a new AnnotationConfigApplicationContext that needs to be populated* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.*/public AnnotationConfigApplicationContext() {StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");// 额外会创建StandardEnvironmentthis.reader = new AnnotatedBeanDefinitionReader(this);createAnnotatedBeanDefReader.end();this.scanner = new ClassPathBeanDefinitionScanner(this);}/*** Create a new AnnotationConfigApplicationContext with the given DefaultListableBeanFactory.** @param beanFactory the DefaultListableBeanFactory instance to use for this context*/public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {super(beanFactory);this.reader = new AnnotatedBeanDefinitionReader(this);this.scanner = new ClassPathBeanDefinitionScanner(this);}/*** Create a new AnnotationConfigApplicationContext, deriving bean definitions* from the given component classes and automatically refreshing the context.** @param componentClasses one or more component classes &mdash; for example,*                         {@link Configuration @Configuration} classes*/public AnnotationConfigApplicationContext(Class<?>... componentClasses) {/*** this之前先调用父类GenericApplicationContext 的构造器,创建 DefaultListableBeanFactory* */// 构造DefaultListableBeanFactory、AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScannerthis();// 将启动类注册到BeanFactoryregister(componentClasses);// 刷新refresh();}/*** Create a new AnnotationConfigApplicationContext, scanning for components* in the given packages, registering bean definitions for those components,* and automatically refreshing the context.** @param basePackages the packages to scan for component classes*/public AnnotationConfigApplicationContext(String... basePackages) {this();scan(basePackages);refresh();}/*** Propagate the given custom {@code Environment} to the underlying* {@link AnnotatedBeanDefinitionReader} and {@link ClassPathBeanDefinitionScanner}.*/@Overridepublic void setEnvironment(ConfigurableEnvironment environment) {super.setEnvironment(environment);this.reader.setEnvironment(environment);this.scanner.setEnvironment(environment);}/*** Provide a custom {@link BeanNameGenerator} for use with {@link AnnotatedBeanDefinitionReader}* and/or {@link ClassPathBeanDefinitionScanner}, if any.* <p>Default is {@link AnnotationBeanNameGenerator}.* <p>Any call to this method must occur prior to calls to {@link #register(Class...)}* and/or {@link #scan(String...)}.** @see AnnotatedBeanDefinitionReader#setBeanNameGenerator* @see ClassPathBeanDefinitionScanner#setBeanNameGenerator* @see AnnotationBeanNameGenerator* @see FullyQualifiedAnnotationBeanNameGenerator*/public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {this.reader.setBeanNameGenerator(beanNameGenerator);this.scanner.setBeanNameGenerator(beanNameGenerator);getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);}/*** Set the {@link ScopeMetadataResolver} to use for registered component classes.* <p>The default is an {@link AnnotationScopeMetadataResolver}.* <p>Any call to this method must occur prior to calls to {@link #register(Class...)}* and/or {@link #scan(String...)}.*/public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {this.reader.setScopeMetadataResolver(scopeMetadataResolver);this.scanner.setScopeMetadataResolver(scopeMetadataResolver);}//---------------------------------------------------------------------// Implementation of AnnotationConfigRegistry//---------------------------------------------------------------------/*** Register one or more component classes to be processed.* <p>Note that {@link #refresh()} must be called in order for the context* to fully process the new classes.** @param componentClasses one or more component classes &mdash; for example,*                         {@link Configuration @Configuration} classes* @see #scan(String...)* @see #refresh()*/@Overridepublic void register(Class<?>... componentClasses) {Assert.notEmpty(componentClasses, "At least one component class must be specified");StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register").tag("classes", () -> Arrays.toString(componentClasses));this.reader.register(componentClasses);registerComponentClass.end();}/*** Perform a scan within the specified base packages.* <p>Note that {@link #refresh()} must be called in order for the context* to fully process the new classes.** @param basePackages the packages to scan for component classes* @see #register(Class...)* @see #refresh()*/@Overridepublic void scan(String... basePackages) {Assert.notEmpty(basePackages, "At least one base package must be specified");StartupStep scanPackages = this.getApplicationStartup().start("spring.context.base-packages.scan").tag("packages", () -> Arrays.toString(basePackages));this.scanner.scan(basePackages);scanPackages.end();}//---------------------------------------------------------------------// Adapt superclass registerBean calls to AnnotatedBeanDefinitionReader//---------------------------------------------------------------------@Overridepublic <T> void registerBean(@Nullable String beanName, Class<T> beanClass,@Nullable Supplier<T> supplier, BeanDefinitionCustomizer... customizers) {this.reader.registerBean(beanClass, beanName, supplier, customizers);}}

通过上述类上的注释,我们大概了解到这是一个Spring的上下文,可以接受添加@Configuration注解的类当成参数,也可以接受一个添加@Component注解的普通Bean当成参数;

AnnotationConfigApplicationContext类的四个构造器:

// 无参构造器
public AnnotationConfigApplicationContext() {StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");this.reader = new AnnotatedBeanDefinitionReader(this);createAnnotatedBeanDefReader.end();this.scanner = new ClassPathBeanDefinitionScanner(this);
}// 参数是DefaultListableBeanFactory 的构造器
public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {super(beanFactory);this.reader = new AnnotatedBeanDefinitionReader(this);this.scanner = new ClassPathBeanDefinitionScanner(this);
}// 参数是Class文件的构造器
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {this();register(componentClasses);refresh();
}// 参数是扫描路径的构造器
public AnnotationConfigApplicationContext(String... basePackages) {this();scan(basePackages);refresh();
}

启动过程详解

这里我们重点分析使用最多的:参数是Class文件的构造器

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {// this之前先调用父类GenericApplicationContext 的构造器,创建 DefaultListableBeanFactory// 构造DefaultListableBeanFactory、AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScannerthis();// 将启动类注册到BeanFactoryregister(componentClasses);// 刷新refresh();}

这里我们可以看到:

  1. 首先会调用无参构造
  2. 调用register()方法将配置类注册到BeanFactory中;
  3. 调用refresh()方法,刷新Spring容器;

无参构造方法

无参构造方法详解

/*** Create a new AnnotationConfigApplicationContext that needs to be populated* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.*/
public AnnotationConfigApplicationContext() {StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");// 额外会创建StandardEnvironmentthis.reader = new AnnotatedBeanDefinitionReader(this);createAnnotatedBeanDefReader.end();this.scanner = new ClassPathBeanDefinitionScanner(this);
}

通过上述代码,我们可以看到:

  1. AnnotationConfigApplicationContext类在调用无参构造方法之前,会先调用父类的无参构造方法,也就是GenericApplicationContext类的无参构造方法,我们先看一下GenericApplicationContext类在构造方法中做啦什么;
  2. 通过对GenericApplicationContext类的分析,发现主要就是创建啦beanFactory;
  3. 然后我们再看AnnotationConfigApplicationContext类自己的无参构造器;
  4. 首先会创建AnnotatedBeanDefinitionReader对象(BeanDefinition读取器:详情请移步至《Spring之底层架构核心概念》)
  5. 再往下创建ClassPathBeanDefinitionScanner扫描器;

返回启动过程详解;

refresh()方法

refresh()方法详解

@Override
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");// Prepare this context for refreshing./*** 准备刷新;* 设置一些初始值、环境变量之类操作* */prepareRefresh();// Tell the subclass to refresh the internal bean factory.// 这里会判断能否刷新,并且返回一个BeanFactory, 刷新不代表完全情况,主要是先执行Bean的销毁,然后重新生成一个BeanFactory,再在接下来的步骤中重新去扫描等等/*** 给BeanFactory设置一个序列化id* 将创建好的BeanFactory对象返回* */ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.// 准备BeanFactory// 1. 设置BeanFactory的类加载器、SpringEL表达式解析器、类型转化注册器// 2. 添加三个BeanPostProcessor,注意是具体的BeanPostProcessor实例对象// 3. 记录ignoreDependencyInterface// 4. 记录ResolvableDependency// 5. 添加三个单例BeanprepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.// 子类来设置一下BeanFactorypostProcessBeanFactory(beanFactory);StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");// Invoke factory processors registered as beans in the context.// BeanFactory准备好了之后,执行BeanFactoryPostProcessor,开始对BeanFactory进行处理// 默认情况下:// 此时beanFactory的beanDefinitionMap中有6个BeanDefinition,5个基础BeanDefinition+AppConfig的BeanDefinition// 而这6个中只有一个BeanFactoryPostProcessor:ConfigurationClassPostProcessor// 这里会执行ConfigurationClassPostProcessor进行@Component的扫描,扫描得到BeanDefinition,并注册到beanFactory中// 注意:扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行//处理 BeanFactoryPostProcessorinvokeBeanFactoryPostProcessors(beanFactory);  // scanner.scan()// Register bean processors that intercept bean creation.// 将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去//处理 BeanPostProcessorsregisterBeanPostProcessors(beanFactory);beanPostProcess.end();// Initialize message source for this context.// 设置ApplicationContext的MessageSource,要么是用户设置的,要么是DelegatingMessageSource// 设置国际化initMessageSource();// Initialize event multicaster for this context.// 设置ApplicationContext的applicationEventMulticaster,要么是用户设置的,要么是SimpleApplicationEventMulticaster//设置事件发布器initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.// 给子类的模板方法onRefresh();// Check for listener beans and register them.// 把定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件//设置 事件监听器registerListeners();// Instantiate all remaining (non-lazy-init) singletons.// 完成 bean工厂 初始化finishBeanFactoryInitialization(beanFactory);// 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();contextRefresh.end();}}
}

通过上述代码,我们可以看到:

  1. 调用prepareRefresh()方法,设置一些初始值、环境变量之类操作;
  2. 调用obtainFreshBeanFactory()方法,获取给BeanFactory设置一个序列化id,并拿到BeanFactory对象;
  3. 调用prepareBeanFactory()方法;
  4. 调用postProcessBeanFactory()方法,给子类来设置一下BeanFactory,SpringMVC会有相关设置,Spring容器是一个空方法;
  5. 调用invokeBeanFactoryPostProcessors()方法,执行BeanFactory的后置处理;
  6. 调用registerBeanPostProcessors()方法,方法名直译就是,注册BeanPostProcessors
  7. 调用initMessageSource()方法,设置国际化;
  8. 调用initApplicationEventMulticaster()方法,设置时间发布器;
  9. onRefresh()方法是给子类的模板方法,SpringMVC会用到;
  10. 调用registerListeners()方法,设置事件监听器;
  11. 调用finishBeanFactoryInitialization()方法,完成bean工厂初始化;
  12. 到这里Spring容器启动成功;

返回启动过程详解;

prepareRefresh()方法

prepareRefresh()方法详解

/*** Prepare this context for refreshing, setting its startup date and* active flag as well as performing any initialization of property sources.*/
protected void prepareRefresh() {// Switch to active.this.startupDate = System.currentTimeMillis();this.closed.set(false);this.active.set(true);if (logger.isDebugEnabled()) {if (logger.isTraceEnabled()) {logger.trace("Refreshing " + this);} else {logger.debug("Refreshing " + getDisplayName());}}// Initialize any placeholder property sources in the context environment.// 比如子类可以把ServletContext中的参数对设置到EnvironmentinitPropertySources();// Validate that all properties marked as required are resolvable:// see ConfigurablePropertyResolver#setRequiredPropertiesgetEnvironment().validateRequiredProperties();// Store pre-refresh ApplicationListeners...if (this.earlyApplicationListeners == null) {this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);} else {// Reset local application listeners to pre-refresh state.this.applicationListeners.clear();this.applicationListeners.addAll(this.earlyApplicationListeners);}// Allow for the collection of early ApplicationEvents,// to be published once the multicaster is available...this.earlyApplicationEvents = new LinkedHashSet<>();
}

这里没什么有营养代码和知识,自行阅读即可;

返回refresh()方法;

prepareBeanFactory()方法

prepareBeanFactory()方法详解

/*** Configure the factory's standard context characteristics,* such as the context's ClassLoader and post-processors.** @param beanFactory the BeanFactory to configure*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {// Tell the internal bean factory to use the context's class loader etc.// 获取类加载器设置给beanFactory,如果前面设置啦类加载器就用设置好的,没设置就用默认的AppClassLoader,beanFactory.setBeanClassLoader(getClassLoader());// Spring5.3中新增的功能,可以选择是否开启Spel功能,shouldIgnoreSpel默认为false,表示开启if (!shouldIgnoreSpel) {// 将spring表达式设置给beanFactorybeanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));}// 添加一个ResourceEditorRegistrar,注册一些默认的类型转化器beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));// Configure the bean factory with context callbacks.// 添加一个BeanPostProcessor,用来处理EnvironmentAware、EmbeddedValueResolverAware等回调beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));// 如果一个属性对应的set方法在ignoredDependencyInterfaces接口中被定义了,则该属性不会进行自动注入(是Spring中的自动注入,不是@Autowired)beanFactory.ignoreDependencyInterface(EnvironmentAware.class);beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);beanFactory.ignoreDependencyInterface(MessageSourceAware.class);beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);// BeanFactory interface not registered as resolvable type in a plain factory.// MessageSource registered (and found for autowiring) as a bean.beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);beanFactory.registerResolvableDependency(ResourceLoader.class, this);beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);beanFactory.registerResolvableDependency(ApplicationContext.class, this);// Register early post-processor for detecting inner beans as ApplicationListeners.// ApplicationListenerDetector负责把ApplicantsListener类型的Bean注册到ApplicationContext中beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));// Detect a LoadTimeWeaver and prepare for weaving, if found.// Aspectj本身是通过编译期进行代理的,在Spring中就跟LoadTimeWeaver有关if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));// Set a temporary ClassLoader for type matching.beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}/*** 将环境变量和Application启动类放入单例池中* */// Register default environment beans.if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());}if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());}if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());}if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());}
}

通过上述代码,我们可以看到:

  1. 首先会给BeanFactory设置类加载器;
  2. 如果shouldIgnoreSpel是false,给BeanFactory设置Spring表达式解析器,shouldIgnoreSpel默认是false;
  3. 再往下,给BeanFactory添加一个ResourceEditorRegistrar,注册一些默认的类型转化器;
  4. 再往下,添加一个ApplicationContextAwareProcessor,用来处理EnvironmentAware、EmbeddedValueResolverAware等回调;
  5. 将EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware、ApplicationStartupAware添加到BeanFactory的ignoredDependencyInterfaces集合中,表示这个几个接口的实现类不会执行spring自带的自动注入@Bean(autowire = Autowire.BY_TYPE),如果实现类有@Autowired、@Inject、@Value、@Resource四个注解还是会执行自动注入;
  6. 将BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext添加到存储类型和对象对应信息的resolvableDependencies中;
  7. 将负责事件监听的ApplicationListenerDetector添加到BeanFactory中的BeanPostProcessor集合中,ApplicationListenerDetector虽然从命名上看不出和BeanPostProcessor的关系,其实他实现啦DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor两个接口;
  8. 在往下这个判断是和Aspectj有关;
  9. 最后,将环境变量和Application启动类放入单例池中;

返回refresh()方法;

invokeBeanFactoryPostProcessors()方法

invokeBeanFactoryPostProcessors()方法详解

/*** Instantiate and invoke all registered BeanFactoryPostProcessor beans,* respecting explicit order if given.* <p>Must be called before singleton instantiation.*/
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)// 关于LoadTimeWeaver看这篇文章了解即可,https://www.cnblogs.com/wade-luffy/p/6073702.htmlif (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}
}

通过上述代码,我们可以看到:

  1. 首先调用PostProcessorRegistrationDelegate类的invokeBeanFactoryPostProcessors()方法;
  2. 下面这个判断和LoadTimeWeaver相关,这里不展开细说;

返回refresh()方法;

registerBeanPostProcessors()方法

registerBeanPostProcessors()方法详解

/*** Instantiate and register all BeanPostProcessor beans,* respecting explicit order if given.* <p>Must be called before any instantiation of application beans.*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

  通过上述代码,我们可以看到,这里会调用PostProcessorRegistrationDelegate类的registerBeanPostProcessors()方法,我们详细分析PostProcessorRegistrationDelegate类的registerBeanPostProcessors()方法;

返回refresh()方法;

finishBeanFactoryInitialization()方法

finishBeanFactoryInitialization()方法详解

/*** Finish the initialization of this context's bean factory,* initializing all remaining singleton beans.*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {// Initialize conversion service for this context.// 如果BeanFactory中存在名字叫conversionService的Bean,则设置为BeanFactory的conversionService属性// ConversionService是用来进行类型转化的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 BeanFactoryPostProcessor// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.// 设置默认的占位符解析器  ${xxx}  ---keyif (!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();
}

通过上述代码,我们可以看到:

  1. 首先判断,如果BeanFactory中存在名字叫conversionService的Bean,则设置为BeanFactory的conversionService属性,ConversionService是用来进行类型转化的;
  2. 设置占位符解析器;
  3. 实例化实现LoadTimeWeaverAware接口的Bean对象;
  4. 调用preInstantiateSingletons()方法,实例化非懒加载的单例Bean;

返回refresh()方法;

GenericApplicationContext对象详解

构造方法

GenericApplicationContext对象构造方法详解

/*** Create a new GenericApplicationContext.* @see #registerBeanDefinition* @see #refresh*/
public GenericApplicationContext() {this.beanFactory = new DefaultListableBeanFactory();
}

GenericApplicationContext对象的无参构造方法也简单,就是创建beanFactory,我们再看一下这个DefaultListableBeanFactory都做啦什么;

返回AnnotationConfigApplicationContext类的无参构造方法

DefaultListableBeanFactory对象详解

构造方法

DefaultListableBeanFactory的构造方法详解

/*** Create a new DefaultListableBeanFactory.*/
public DefaultListableBeanFactory() {super();
}

这里我们可以看到,DefaultListableBeanFactory类在构造方法中什么都没干,只是调用父类的构造方法,我们再看一下他父类的构造方法:

/*** Create a new AbstractAutowireCapableBeanFactory.*/
public AbstractAutowireCapableBeanFactory() {super();/*** 将 BeanNameAware、BeanFactoryAware、BeanClassLoaderAware 添加到* ignoredDependencyInterfaces属性中,表示自动注入时会忽略所有* 实现 BeanNameAware、BeanFactoryAware、BeanClassLoaderAware接口的类* */ignoreDependencyInterface(BeanNameAware.class);ignoreDependencyInterface(BeanFactoryAware.class);ignoreDependencyInterface(BeanClassLoaderAware.class);if (NativeDetector.inNativeImage()) {this.instantiationStrategy = new SimpleInstantiationStrategy();} else {this.instantiationStrategy = new CglibSubclassingInstantiationStrategy();}
}

AbstractAutowireCapableBeanFactory类(DefaultListableBeanFactory的父类)在构造方法中我们可以看到:

  1. 同样先调用父类构造方法,在AbstractBeanFactory类(AbstractAutowireCapableBeanFactory的父类)的构造方法中什么都没做;
  2. 然后依次调用ignoreDependencyInterface()方法,将 BeanNameAware、BeanFactoryAware、BeanClassLoaderAware 添加到ignoredDependencyInterfaces属性中,表示自动注入时会忽略所有实现 BeanNameAware、BeanFactoryAware、BeanClassLoaderAware接口的类;
  3. 再往下,NativeDetector.inNativeImage(),这个判断是判断我们是否使用graalvm;
  4. 一般情况我肯定是false,然后创建Cglib的实例化策略;

返回GenericApplicationContext类;

preInstantiateSingletons()方法

preInstantiateSingletons()方法详解

@Override
public void preInstantiateSingletons() throws BeansException {if (logger.isTraceEnabled()) {logger.trace("Pre-instantiating singletons in " + this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);// Trigger initialization of all non-lazy singleton beans...for (String beanName : beanNames) {// 获取合并后的BeanDefinitionRootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {if (isFactoryBean(beanName)) {// 获取FactoryBean对象Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);if (bean instanceof FactoryBean) {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) {// 创建真正的Bean对象(getObject()返回的对象)getBean(beanName);}}} else {// 创建Bean对象getBean(beanName);}}}System.out.println("=====调用SmartInitializingSingleton接口的afterSingletonsInstantiated方法=====");// 所有的非懒加载单例Bean都创建完了后// Trigger post-initialization callback for all applicable beans...for (String beanName : beanNames) {Object singletonInstance = getSingleton(beanName);if (singletonInstance instanceof SmartInitializingSingleton) {StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {smartSingleton.afterSingletonsInstantiated();return null;}, getAccessControlContext());} else {smartSingleton.afterSingletonsInstantiated();}smartInitialize.end();}}
}

此方法详情,请移步至《Spring之Bean生命周期~合并BeanDefinition》;

返回finishBeanFactoryInitialization()方法;

AnnotatedBeanDefinitionReader对象详解

构造方法

AnnotatedBeanDefinitionReader对象构造方法详解

/*** Create a new {@code AnnotatedBeanDefinitionReader} for the given registry.* <p>If the registry is {@link EnvironmentCapable}, e.g. is an {@code ApplicationContext},* the {@link Environment} will be inherited, otherwise a new* {@link StandardEnvironment} will be created and used.** @param registry the {@code BeanFactory} to load bean definitions into,*                 in the form of a {@code BeanDefinitionRegistry}* @see #AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment)* @see #setEnvironment(Environment)*/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {// getOrCreateEnvironment方法 创建环境变量this(registry, getOrCreateEnvironment(registry));
}/*** Create a new {@code AnnotatedBeanDefinitionReader} for the given registry,* using the given {@link Environment}.** @param registry    the {@code BeanFactory} to load bean definitions into,*                    in the form of a {@code BeanDefinitionRegistry}* @param environment the {@code Environment} to use when evaluating bean definition*                    profiles.* @since 3.1*/
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");Assert.notNull(environment, "Environment must not be null");this.registry = registry;// 用来解析@Conditional(条件注解)注解的this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);// 注册AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

通过上述代码,我们可以看到:

  1. AnnotationConfigApplicationContext的无参构造器在创建AnnotatedBeanDefinitionReader对象时,是通过无参构造器创建的;
  2. 无参构造方法先调用getOrCreateEnvironment()方法获取到环境变量;
  3. 然后又调用啦有参构造器;
  4. 首先通过ConditionEvaluator的有参构造方法创建ConditionEvaluator对象(用来解析@Conditional(条件注解)注解的);
  5. 调用AnnotationConfigUtils类的registerAnnotationConfigProcessors()方法,注册我么后续用到的一些AnnotationAwareOrderComparator比较器、ContextAnnotationAutowireCandidateResolver候选解析器和一些后置处理器;

返回AnnotationConfigApplicationContext类的无参构造方法

ConditionEvaluator对象

构造方法

ConditionEvaluator对象构造方法详解

/*** Create a new {@link ConditionEvaluator} instance.*/
public ConditionEvaluator(@Nullable BeanDefinitionRegistry registry,@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {this.context = new ConditionContextImpl(registry, environment, resourceLoader);
}

  这里我们可以看到ConditionEvaluator在构造方法中创建啦ConditionContextImpl对象,而ConditionContextImpl对象是ConditionEvaluator的静态内部类,我们再分析ConditionContextImpl这个静态内部类;

public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry,@Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {this.registry = registry;this.beanFactory = deduceBeanFactory(registry);this.environment = (environment != null ? environment : deduceEnvironment(registry));this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));this.classLoader = deduceClassLoader(resourceLoader, this.beanFactory);
}

通过上述代码我们可以看到;

  1. 首先设置registry 属性,registry 属性是我们一开始传进来的AnnotationConfigApplicationContext对象(Spring容器);
  2. 然后调用deduceBeanFactory()方法获取BeanFactory;
  3. 获取environment (环境变量);
  4. 设置resourceLoader (资源读取器);
  5. 设置classLoader (类加载器);

返回AnnotatedBeanDefinitionReader对象详解

AnnotationConfigUtils对象

registerAnnotationConfigProcessors()方法

registerAnnotationConfigProcessors()方法详解

/*** Register all relevant annotation post processors in the given registry.** @param registry the registry to operate on*/
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {registerAnnotationConfigProcessors(registry, null);
}/*** Register all relevant annotation post processors in the given registry.** @param registry the registry to operate on* @param source   the configuration source element (already extracted)*                 that this registration was triggered from. May be {@code null}.* @return a Set of BeanDefinitionHolders, containing all bean definitions* that have actually been registered by this call*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);if (beanFactory != null) {// 设置beanFactory的OrderComparator为AnnotationAwareOrderComparator// 它是一个Comparator,是一个比较器,可以用来进行排序,比如new ArrayList<>().sort(Comparator);if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);}// 用来判断某个Bean能不能用来进行依赖注入if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());}}Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);// 注册ConfigurationClassPostProcessor类型的BeanDefinitionif (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));}// 注册AutowiredAnnotationBeanPostProcessor类型的BeanDefinitionif (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));}// 注册CommonAnnotationBeanPostProcessor类型的BeanDefinition// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));}// 注册PersistenceAnnotationBeanPostProcessor类型的BeanDefinition// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition();try {def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,AnnotationConfigUtils.class.getClassLoader()));} catch (ClassNotFoundException ex) {throw new IllegalStateException("Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);}def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));}// 注册EventListenerMethodProcessor类型的BeanDefinition,用来处理@EventListener注解的if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));}// 注册DefaultEventListenerFactory类型的BeanDefinition,用来处理@EventListener注解的if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));}return beanDefs;
}

  通过上述代码我们可以看到,registerAnnotationConfigProcessors方法有一个重载方法,接下来我们详细分析registerAnnotationConfigProcessors方法中的处理逻辑:

  1. 调用unwrapDefaultListableBeanFactory()方法获取beanFactory;
  2. 再往下,如果beanFactory没有设置AnnotationAwareOrderComparator比较器的话,设置一下AnnotationAwareOrderComparator比较器,AnnotationAwareOrderComparator比较器的作用:可以根据@Priority注解、Ordered接口和@Order注解设置的值进行排序;
  3. 再往下,如果beanFactory没有设置ContextAnnotationAutowireCandidateResolver候选解析器的话,设置一下ContextAnnotationAutowireCandidateResolver候选解析器,ContextAnnotationAutowireCandidateResolver候选解析器的作用:判断某个bean针对当前依赖是否能注入;比如@Bean注解中autowireCandidate属性设置成false是不能注入给其他bean的;
  4. 再往下,将ConfigurationClassPostProcessor设置成BeanDefinition,并添加到beanDefs中;(ConfigurationClassPostProcessorl类的postProcessBeanDefinitionRegistry方法会解析配置类,触发扫描);
  5. 再往下,将AutowiredAnnotationBeanPostProcessor设置成BeanDefinition,并添加到beanDefs中;AutowiredAnnotationBeanPostProcessor的作用:会扫描@Autowired、@Value、@Inject注入点,对注入点进行依赖注入,详情请移步至《Spring之Bean生命周期~依赖注入(2)》
  6. 再往下,将CommonAnnotationBeanPostProcessor设置成BeanDefinition,并添加到beanDefs中;CommonAnnotationBeanPostProcessor的作用:会扫描@Resource注入点,对注入点进行依赖注入,详情请移步至《Spring之Bean生命周期~依赖注入(3)》;
  7. 再往下,如果是JPA会注册PersistenceAnnotationBeanPostProcessor,没有JPA不会进入判断;
  8. 再往下,依次将EventListenerMethodProcessor和DefaultEventListenerFactory设置成BeanDefinition,并添加到beanDefs中;EventListenerMethodProcessor和DefaultEventListenerFactory的作用:处理@EventListener注解的;

返回AnnotatedBeanDefinitionReader对象;

unwrapDefaultListableBeanFactory()方法

unwrapDefaultListableBeanFactory()方法详解

@Nullable
private static DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) {if (registry instanceof DefaultListableBeanFactory) {return (DefaultListableBeanFactory) registry;} else if (registry instanceof GenericApplicationContext) {return ((GenericApplicationContext) registry).getDefaultListableBeanFactory();} else {return null;}
}

  通过上述代码,我们可以看到这里主要是获取BeanFactory对象,因为我们之前是通过GenericApplicationContext创建的BeanFactory,所以合理会走GenericApplicationContext类的getDefaultListableBeanFactory()方法拿到之前创建好的BeanFactory对象;

返回registerAnnotationConfigProcessors()方法

ClassPathBeanDefinitionScanner对象

构造方法

ClassPathBeanDefinitionScanner构造方法详解

/*** Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.** @param registry the {@code BeanFactory} to load bean definitions into, in the form*                 of a {@code BeanDefinitionRegistry}*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {this(registry, true);
}/*** Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.* <p>If the passed-in bean factory does not only implement the* {@code BeanDefinitionRegistry} interface but also the {@code ResourceLoader}* interface, it will be used as default {@code ResourceLoader} as well. This will* usually be the case for {@link org.springframework.context.ApplicationContext}* implementations.* <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}* will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.* <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its* environment will be used by this reader.  Otherwise, the reader will initialize and* use a {@link org.springframework.core.env.StandardEnvironment}. All* {@code ApplicationContext} implementations are {@code EnvironmentCapable}, while* normal {@code BeanFactory} implementations are not.** @param registry          the {@code BeanFactory} to load bean definitions into, in the form*                          of a {@code BeanDefinitionRegistry}* @param useDefaultFilters whether to include the default filters for the*                          {@link org.springframework.stereotype.Component @Component},*                          {@link org.springframework.stereotype.Repository @Repository},*                          {@link org.springframework.stereotype.Service @Service}, and*                          {@link org.springframework.stereotype.Controller @Controller} stereotype annotations* @see #setResourceLoader* @see #setEnvironment*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}/*** Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and* using the given {@link Environment} when evaluating bean definition profile metadata.* <p>If the passed-in bean factory does not only implement the {@code* BeanDefinitionRegistry} interface but also the {@link ResourceLoader} interface, it* will be used as default {@code ResourceLoader} as well. This will usually be the* case for {@link org.springframework.context.ApplicationContext} implementations.* <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}* will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.** @param registry          the {@code BeanFactory} to load bean definitions into, in the form*                          of a {@code BeanDefinitionRegistry}* @param useDefaultFilters whether to include the default filters for the*                          {@link org.springframework.stereotype.Component @Component},*                          {@link org.springframework.stereotype.Repository @Repository},*                          {@link org.springframework.stereotype.Service @Service}, and*                          {@link org.springframework.stereotype.Controller @Controller} stereotype annotations* @param environment       the Spring {@link Environment} to use when evaluating bean*                          definition profile metadata* @see #setResourceLoader* @since 3.1*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,Environment environment) {this(registry, useDefaultFilters, environment,(registry instanceof ResourceLoader ? (ResourceLoader) registry : null));
}/*** Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and* using the given {@link Environment} when evaluating bean definition profile metadata.** @param registry          the {@code BeanFactory} to load bean definitions into, in the form*                          of a {@code BeanDefinitionRegistry}* @param useDefaultFilters whether to include the default filters for the*                          {@link org.springframework.stereotype.Component @Component},*                          {@link org.springframework.stereotype.Repository @Repository},*                          {@link org.springframework.stereotype.Service @Service}, and*                          {@link org.springframework.stereotype.Controller @Controller} stereotype annotations* @param environment       the Spring {@link Environment} to use when evaluating bean*                          definition profile metadata* @param resourceLoader    the {@link ResourceLoader} to use* @since 4.3.6*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,Environment environment, @Nullable ResourceLoader resourceLoader) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");this.registry = registry;if (useDefaultFilters) {registerDefaultFilters();}setEnvironment(environment);setResourceLoader(resourceLoader);
}

通过上述代码跟踪,最终调到啦参数最多的构造器,我们详细分析参数最多的构造方法:

  1. 一个参数构造器调用两个参数构造器时,手动设置啦useDefaultFilters是true;
  2. 调用registerDefaultFilters()方法,将@Component注解添加到includeFilters过滤器中;
  3. 设置环境变量和资源加载器;

返回AnnotationConfigApplicationContext的无参构造方法

registerDefaultFilters()方法

registerDefaultFilters()方法详解

/*** Register the default filter for {@link Component @Component}.* <p>This will implicitly register all annotations that have the* {@link Component @Component} meta-annotation including the* {@link Repository @Repository}, {@link Service @Service}, and* {@link Controller @Controller} stereotype annotations.* <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and* JSR-330's {@link javax.inject.Named} annotations, if available.*/
@SuppressWarnings("unchecked")
protected void registerDefaultFilters() {// 注册@Component对应的AnnotationTypeFilterthis.includeFilters.add(new AnnotationTypeFilter(Component.class));ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();try {this.includeFilters.add(new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");} catch (ClassNotFoundException ex) {// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.}try {this.includeFilters.add(new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");} catch (ClassNotFoundException ex) {// JSR-330 API not available - simply skip.}
}

通过上述代码,我们可以看到:

  1. 首先将@Component注解添加到includeFilters过滤器中;
  2. 接下来是添加@ManagedBean注解和@Named注解,这两个都是java自带注解,使用不多,不展开细讲;

返回ClassPathBeanDefinitionScanner类的构造方法

PostProcessorRegistrationDelegate对象

invokeBeanFactoryPostProcessors()方法

invokeBeanFactoryPostProcessors()方法详解

/*** BeanFactoryPostProcessors按入场方式分为:* 1. 程序员调用ApplicationContext的API手动添加* 2. Spring自己扫描出来的* <p>* BeanFactoryPostProcessor按类型又可以分为:* 1. 普通BeanFactoryPostProcessor* 2. BeanDefinitionRegistryPostProcessor* <p>* 执行顺序顺序如下:* 1. 执行手动添加的BeanDefinitionRegistryPostProcessor                       的postProcessBeanDefinitionRegistry()方法* 2. 执行扫描出来的BeanDefinitionRegistryPostProcessor(实现了PriorityOrdered)的postProcessBeanDefinitionRegistry()方法* 3. 执行扫描出来的BeanDefinitionRegistryPostProcessor(实现了Ordered)		   的postProcessBeanDefinitionRegistry()方法* 4. 执行扫描出来的BeanDefinitionRegistryPostProcessor(普通)				   的postProcessBeanDefinitionRegistry()方法* 5. 执行扫描出来的BeanDefinitionRegistryPostProcessor(所有)				   的postProcessBeanFactory()方法* 6. 执行手动添加的BeanFactoryPostProcessor								   的postProcessBeanFactory()方法* 7. 执行扫描出来的BeanFactoryPostProcessor(实现了PriorityOrdered)		   的postProcessBeanFactory()方法* 8. 执行扫描出来的BeanFactoryPostProcessor(实现了Ordered)		   		   的postProcessBeanFactory()方法* 9. 执行扫描出来的BeanFactoryPostProcessor(普通)				   		   的postProcessBeanFactory()方法* <p>* ConfigurationClassPostProcessor就会在第2步执行,会进行扫描*/
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {   // BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor// Invoke BeanDefinitionRegistryPostProcessors first, if any.Set<String> processedBeans = new HashSet<>();// 实现BeanDefinitionRegistry接口的beanFactory具有注册、保存、移除、获取某个BeanDefinition的功能if (beanFactory instanceof BeanDefinitionRegistry) {BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();// beanFactoryPostProcessors集合一般情况下都是空的,除非我们手动调用容器的addBeanFactoryPostProcessor方法添加了// beanFactoryPostProcessors中可能包含了:普通BeanFactoryPostProcessor对象和BeanDefinitionRegistryPostProcessor对象// 对于BeanDefinitionRegistryPostProcessor对象,会执行自己的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<>();/*****************************************************************************/// 执行扫描出来的BeanDefinitionRegistryPostProcessor// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.// 此方法能拿到 ConfigurationClassPostProcessor 对象String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {// 判断 ConfigurationClassPostProcessor 是否实现 PriorityOrdered接口if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {// 创建bean对象 添加到BeanDefinitionRegistryPostProcessor类型的对象集合中currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}// 升序排序sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);// 执行 ConfigurationClassPostProcessor对象的postProcessBeanDefinitionRegistry对象进行扫描invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();/*****************************************************************************/// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {// processedBeans表示该beanFactoryPostProcessor的postProcessBeanDefinitionRegistry()方法已经执行过了,不再重复执行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, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();/*****************************************************************************/// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.// 执行哪些没有实现了PriorityOrdered或Ordered接口的普通BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法// 在这个过程中可能会向BeanFactory中注册另外的BeanDefinitionRegistryPostProcessor,所以需要while,直到确定所有的BeanDefinitionRegistryPostProcessor都执行完了// 在这个过程中注册的BeanDefinitionRegistryPostProcessor,所实现的PriorityOrdered或Ordered接口可能会不按顺序执行// 比如 A注册了B和C,B又注册了D和E,那么B和C会按顺序执行,D和E也会按顺序执行,但是B、C、D、E整体不能保证是顺序执行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, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();}/*****************************************************************************/// Now, invoke the postProcessBeanFactory callback of all processors handled so far.// 执行完BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法后,// 再执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法// 执行设置BeanDefinition的方法invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);// 执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);} else {// Invoke factory processors registered with the context instance.invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);}// 执行扫描出来的普通BeanFactoryPostProcessor// 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<>(orderedPostProcessorNames.size());for (String postProcessorName : orderedPostProcessorNames) {orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}sortPostProcessors(orderedPostProcessors, beanFactory);invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);// Finally, invoke all other BeanFactoryPostProcessors.List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());for (String postProcessorName : nonOrderedPostProcessorNames) {nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);// Clear cached merged bean definitions since the post-processors might have// modified the original metadata, e.g. replacing placeholders in values...beanFactory.clearMetadataCache();
}

通过上述代码,我们可以看到:

  1. 首先判读BeanFactory是否实现BeanDefinitionRegistry接口,实现BeanDefinitionRegistry接口的beanFactory具有注册、保存、移除、获取某个BeanDefinition的功能;
  2. 如果没有实现,调用invokeBeanFactoryPostProcessors()方法,执行所以BeanFactoryPostProcessor的postProcessBeanFactory()方法;
  3. 如果实现啦,
  4. 遍历所有的BeanFactoryPostProcessor,此时BeanFactoryPostProcessor集合中还是空的;
  5. 再往下,从BeanFactory中拿到实现BeanDefinitionRegistryPostProcessor接口的Bean,这里只是拿到BeanName;(这里可以拿到AnnotationConfigApplicationContext无参构造器时添加的ConfigurationClassPostProcessor对象);
  6. 遍历这些BeanName,判断如果实现PriorityOrdered接口的话,调用getBean方法进行实例化,其实就是创建ConfigurationClassPostProcessor Bean对象;
  7. 调用sortPostProcessors()方法进行排序;
  8. 再往下执行invokeBeanDefinitionRegistryPostProcessors()方法,这里会执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry()方法,其实就是执行上面ConfigurationClassPostProcessor Bean对象的postProcessBeanDefinitionRegistry()方法;完成Bean对象的扫描;
  9. 再往下,再次从BeanFactory中获取实现BeanDefinitionRegistryPostProcessor接口的BeanName;
  10. 这里的作用是拿到我们自己设置的实现BeanDefinitionRegistryPostProcessor接口的Bean,上一步是拿到Spring容器设置的ConfigurationClassPostProcessor Bean;
  11. 拿到所有的实现BeanDefinitionRegistryPostProcessor接口的BeanName后,过滤掉已经执行过的(ConfigurationClassPostProcessor Bean对象),通过getBean方法创建Bean对象;
  12. 然后进行排序,执行他们的postProcessBeanDefinitionRegistry()方法;
  13. 再往下,这个while()循环的作用:担心前两步会漏掉,有实现BeanDefinitionRegistryPostProcessor接口的Bean没有执行postProcessBeanDefinitionRegistry()方法,这里再做一个补充;
  14. 这里调用invokeBeanFactoryPostProcessors()方法,执行所有实现BeanDefinitionRegistryPostProcessor接口Bean对象的postProcessBeanFactory()方法,(这里包括执行ConfigurationClassPostProcessor Bean对象的postProcessBeanFactory()方法,详情请移步至《Spring~配置类》);
  15. 再往下执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法;
  16. 拿到所有实现BeanFactoryPostProcessor接口的类,先进行筛选和分类,过滤掉前面执行过的,根据PriorityOrdered、Ordered、没有实现任何排序接口三种情况进行分类,根据PriorityOrdered、Ordered、没有实现任何排序接口的顺序执行,先创建bean对象,在执行对象的postProcessBeanFactory方法;

返回AnnotationConfigApplicationContext类的invokeBeanFactoryPostProcessors()方法;

registerBeanPostProcessors()方法

registerBeanPostProcessors()方法详解

public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {// 获取到所有的BeanPostProcessorString[] 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.// beanProcessorTargetCount表示BeanFactory中所有的BeanPostProcessor数量,+1表示BeanPostProcessorCheckerint beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));// Separate between BeanPostProcessors that implement PriorityOrdered,// Ordered, and the rest.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);}}// First, register the BeanPostProcessors that implement PriorityOrdered.// 升序排序sortPostProcessors(priorityOrderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);// Next, register the BeanPostProcessors that implement Ordered.List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());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.List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());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.// MergedBeanDefinitionPostProcessor排在最后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).// ApplicationListenerDetector放在所有BeanPostProcessor之后,注意ApplicationListenerDetector的equals()方法实现beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));}

通过上述代码,我们可以看到:

  1. 首先会拿到所有实现啦BeanPostProcessor接口的BeanName;
  2. 将所有的BeanPostProcessor注册到BeanFactory中;
  3. 再往下,根据PriorityOrdered、Ordered、没有实现任何排序接口三种情况进行分类;
  4. 根据上面的顺序,先创建bean对象,把bean对象安装顺序添加到BeanFactory的beanPostProcessors属性中;
  5. 最后把ApplicationListenerDetector添加到BeanFactory的beanPostProcessors属性中;

返回AnnotationConfigApplicationContext类的registerBeanPostProcessors()方法;

ConfigurationClassPostProcessor 对象

postProcessBeanDefinitionRegistry()方法

postProcessBeanDefinitionRegistry()方法详解

/*** Derive further bean definitions from the configuration classes in the registry.*/
@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);
}

通过上述代码,我们可以看到,这里会调用processConfigBeanDefinitions()方法解析配置类,详情请移步至《Spring~配置类》

返回PostProcessorRegistrationDelegate类的invokeBeanFactoryPostProcessors()方法;

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com