当前位置:   article > 正文

Spring启动过程_spring 启动过程

spring 启动过程

Spring启动就是在初始化相关对象(BeanFactory)与调用refresh()方法

这里以 AnnotationConfigApplicationContext 为例

初始化:

  1. public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
  2. // 通过父级 构造 DefaultListableBeanFactory
  3. // 通过 new 创建AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner对象
  4. this();
  5. // 注册配置类 BeanDefinition 容器中
  6. register(componentClasses);
  7. // 加载或刷新容器中的Bean
  8. refresh();
  9. }

流程总结:

  1. 注册Spring相关的类型。
  2. 将配置类注册到BeanDefinition中。
  3. 加载或刷新容器中的Bean

执行this方法:

  1. public AnnotationConfigApplicationContext() {
  2. // 一种计时的东西
  3. StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
  4. this.reader = new AnnotatedBeanDefinitionReader(this);
  5. createAnnotatedBeanDefReader.end();
  6. this.scanner = new ClassPathBeanDefinitionScanner(this);
  7. }
  8. // 父类初始化加载 DefaultListableBeanFactory
  9. public GenericApplicationContext() {
  10. this.beanFactory = new DefaultListableBeanFactory();
  11. }

流程总结:

  1. 父类初始化生成DefaultListableBeanFactory类。
  2. 创建AnnotatedBeanDefinitionReader对象
    1. 使用ASM技术,读取class的相关对象。
    2. 初始化用来解析@Conditional注解的ConditionEvaluator类。
    3. 注册Spring自带的类,如:ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor 等
  1. 构建一个扫描的类,用来扫描包或类转换成BeanDefinition。

构建AnnotatedBeanDefinitionReader对象

  1. public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
  2. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  3. Assert.notNull(environment, "Environment must not be null");
  4. this.registry = registry;
  5. // 注册扫描@Conditional的类
  6. this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
  7. AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
  8. }
  9. public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
  10. BeanDefinitionRegistry registry, @Nullable Object source) {
  11. // 进行类型的转换,将BeanDefinitionRegistry转换成 DefaultListableBeanFactory
  12. DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
  13. if (beanFactory != null) {
  14. // 构建一个 AnnotationAwareOrderComparator 比较器 用来后面对Order和Priority进行排序
  15. if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
  16. beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
  17. }
  18. // 用来判断Bean能不能进行依赖注入
  19. if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
  20. beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
  21. }
  22. }
  23. Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
  24. // ConfigurationClassPostProcessor添加到BeanDefinition中
  25. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  26. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  27. def.setSource(source);
  28. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
  29. }
  30. // AutowiredAnnotationBeanPostProcessor 添加到BeanDefinition中
  31. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  32. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
  33. def.setSource(source);
  34. beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  35. }
  36. // CommonAnnotationBeanPostProcessor 添加到BeanDefinition中 @Resource、@PostConstruct @PreDestory注解
  37. if (jakartaAnnotationsPresent && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  38. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
  39. def.setSource(source);
  40. beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
  41. }
  42. // jsr250Present 添加一个internalJsr250AnnotationProcessor后置处理器
  43. if (jsr250Present && !registry.containsBeanDefinition(JSR250_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  44. try {
  45. RootBeanDefinition def = new RootBeanDefinition(InitDestroyAnnotationBeanPostProcessor.class);
  46. def.getPropertyValues().add("initAnnotationType", classLoader.loadClass("javax.annotation.PostConstruct"));
  47. def.getPropertyValues().add("destroyAnnotationType", classLoader.loadClass("javax.annotation.PreDestroy"));
  48. def.setSource(source);
  49. beanDefs.add(registerPostProcessor(registry, def, JSR250_ANNOTATION_PROCESSOR_BEAN_NAME));
  50. }
  51. catch (ClassNotFoundException ex) {
  52. }
  53. }
  54. // 如果你的系统中启用了JPA的方式,那么这里添加一个JPA的后置处理器
  55. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  56. RootBeanDefinition def = new RootBeanDefinition();
  57. try {
  58. def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
  59. AnnotationConfigUtils.class.getClassLoader()));
  60. }
  61. catch (ClassNotFoundException ex) {
  62. throw new IllegalStateException(
  63. "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
  64. }
  65. def.setSource(source);
  66. beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
  67. }
  68. // 注册EventListenerMethodProcessor类型的BeanDefinition,用来处理@EventListener注解的
  69. if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
  70. RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
  71. def.setSource(source);
  72. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
  73. }
  74. // 注册DefaultEventListenerFactory类型的BeanDefinition,用来处理@EventListener注解的
  75. if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
  76. RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
  77. def.setSource(source);
  78. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
  79. }
  80. return beanDefs;
  81. }

流程总结:

  1. 添加一个默认比较器。
  2. 构建一个筛选器,判断Bean能不能进行依赖注入等。
  3. 添加ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,EventListenerMethodProcessor,DefaultEventListenerFactory成为BeanDefinition。

构建ClassPathBeanDefinitionScanner对象

  1. public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
  2. Environment environment, @Nullable ResourceLoader resourceLoader) {
  3. Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
  4. this.registry = registry;
  5. // 这里会根据 useDefaultFilters 选择是否注册对应的 TypeFilter
  6. if (useDefaultFilters) {
  7. // 注册@Component对应的AnnotationTypeFilter
  8. // 扫描的时候扫这个注解
  9. registerDefaultFilters();
  10. }
  11. // 设置环境
  12. setEnvironment(environment);
  13. // 设置资源加载路径 (扫描路径)
  14. setResourceLoader(resourceLoader);
  15. }

流程总结:

  1. 在IOC容器中初始化一个 按类路径扫描注解bean的 扫描器
  2. 初始化@Component、@Repository、@Service、@Controller、@ManagedBean、@Named可以被扫描到。
  3. 定义扫描逻辑,将类路径下所有符合的普通类生成BeanDefinition放入BeanDefinitionMap中。

执行regist方法:

  1. public void register(Class<?>... componentClasses) {
  2. for (Class<?> componentClass : componentClasses) {
  3. /**
  4. 将配置类注册到BeanDefinition当中
  5. */
  6. registerBean(componentClass);
  7. }
  8. }
  9. private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
  10. @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
  11. @Nullable BeanDefinitionCustomizer[] customizers) {
  12. AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
  13. //@Conditional装配条件判断是否需要跳过注册
  14. if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
  15. return;
  16. }
  17. // 设置回调
  18. abd.setInstanceSupplier(supplier);
  19. // 解析@Scope注解的结果为ScopeMetadata
  20. ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
  21. abd.setScope(scopeMetadata.getScopeName());
  22. // 生成配置类的BeanName
  23. String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
  24. // 通用注解解析到abd结构中,主要是处理Lazy, primary DependsOn, Role ,Description这五个注解
  25. AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
  26. if (qualifiers != null) {
  27. for (Class<? extends Annotation> qualifier : qualifiers) {
  28. if (Primary.class == qualifier) {
  29. abd.setPrimary(true);
  30. }
  31. else if (Lazy.class == qualifier) {
  32. abd.setLazyInit(true);
  33. }
  34. else {
  35. abd.addQualifier(new AutowireCandidateQualifier(qualifier));
  36. }
  37. }
  38. }
  39. if (customizers != null) {
  40. for (BeanDefinitionCustomizer customizer : customizers) {
  41. customizer.customize(abd);
  42. }
  43. }
  44. BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  45. definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  46. BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
  47. }

流程总结:

  1. 主要就是将配置类扫描成BeanDefinition放入BeanDefinitionMap中。
  2. 解析配置类的相关注解等。

总结:

初始化到这里位置,总共存在6个类存在于BeanDefinitionMap当中

  1. ConfigurationClassPostProcessor:配置类解析器,后面扫描类。
  2. EventListenerMethodProcessor、DefaultEventListenerFactory:事件监听器。
  3. AutowiredAnnotationBeanPostProcessor:@AutoWired依赖注入。
  4. CommonAnnotationBeanPostProcessor:@Resource依赖注入,生命周期回调。
  5. 配置类。

refresh()方法

  1. public void refresh() throws BeansException, IllegalStateException {
  2. synchronized (this.startupShutdownMonitor) {
  3. StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
  4. // Prepare this context for refreshing.
  5. //容器启动前准备工作,也就是设置容器当前的状态和记录启动开始时间以及初始化资源数据以及验证下我们需要验证的一些资源key是否存在
  6. prepareRefresh();
  7. // Tell the subclass to refresh the internal bean factory.
  8. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  9. // Prepare the bean factory for use in this context.
  10. // 准备BeanFactory
  11. // 1. 设置BeanFactory的类加载器、SpringEL表达式解析器、类型转化注册器
  12. // 2. 添加三个BeanPostProcessor,注意是具体的BeanPostProcessor实例对象
  13. // 3. 记录ignoreDependencyInterface
  14. // 4. 记录ResolvableDependency
  15. // 5. 添加三个单例Bean
  16. // 6. 将系统的环境信息、spring容器的启动环境信息、操作系统的环境信息直接注册成一个单例的bean
  17. // 7. 去除一些在byType或者byName的时候需要过滤掉的一些bean(spring在依赖注入的时候会先在这些默认注册的bean中进行byType找
  18. // 如果找到了,就加入到列表中,简单来说就是比如你在bean中依赖注入了ApplicationContext context,那么spring会把默认注册的这些bean 中找到然后进行注册)
  19. prepareBeanFactory(beanFactory);
  20. try {
  21. // Allows post-processing of the bean factory in context subclasses.
  22. // 版本方法,留给子类使用
  23. postProcessBeanFactory(beanFactory);
  24. StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
  25. // Invoke factory processors registered as beans in the context.
  26. // BeanFactory准备好了之后,执行BeanFactoryPostProcessor,开始对BeanFactory进行处理
  27. // 这里就是调用后置处理器,程序执行到这里为止,还没有添加的有我们用户自定义的后置处理器
  28. // 这里会执行ConfigurationClassPostProcessor进行@Component的扫描,扫描得到BeanDefinition,并注册到beanFactory中
  29. // 处理@Import注解
  30. // 如果我们的配置类是@Configuration的,那么会生成这个配置类的CGLIB代理类,如果没有加@Configuration,则就是一个普通Bean
  31. // 注意:扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行
  32. invokeBeanFactoryPostProcessors(beanFactory);
  33. // Register bean processors that intercept bean creation.
  34. // 将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去
  35. registerBeanPostProcessors(beanFactory);
  36. beanPostProcess.end();
  37. // Initialize message source for this context.
  38. // 初始化国际化资源
  39. // 设置ApplicationContext的MessageSource,要么是用户设置的,要么是DelegatingMessageSource
  40. initMessageSource();
  41. // Initialize event multicaster for this context.
  42. // 事件注册器初始化
  43. // 设置ApplicationContext的applicationEventMulticaster,要么是用户设置的,要么是SimpleApplicationEventMulticaster
  44. initApplicationEventMulticaster();
  45. // Initialize other special beans in specific context subclasses.
  46. // 版本方法留个子类使用
  47. onRefresh();
  48. // Check for listener beans and register them.
  49. // 将容器中和BeanDefinitionMap中的监听器添加到事件监听器中
  50. // 把定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件
  51. registerListeners();
  52. // Instantiate all remaining (non-lazy-init) singletons.
  53. // 创建单例池,创建非懒加载的单例bean放入到单例池当中
  54. finishBeanFactoryInitialization(beanFactory);
  55. // Last step: publish corresponding event.
  56. // 容器启动过后,发布事件
  57. finishRefresh();
  58. }
  59. catch (BeansException ex) {
  60. if (logger.isWarnEnabled()) {
  61. logger.warn("Exception encountered during context initialization - " +
  62. "cancelling refresh attempt: " + ex);
  63. }
  64. // Destroy already created singletons to avoid dangling resources.
  65. destroyBeans();
  66. // Reset 'active' flag.
  67. cancelRefresh(ex);
  68. // Propagate exception to caller.
  69. throw ex;
  70. }
  71. finally {
  72. // Reset common introspection caches in Spring's core, since we
  73. // might not ever need metadata for singleton beans anymore...
  74. resetCommonCaches();
  75. contextRefresh.end();
  76. }
  77. }
  78. }

流程总结:

  1. 容器启动工作,加载好相关的类。
  2. 准备工厂,初始化一个后置处理器供后面使用。
  3. 通过bean工厂的后置处理器去处理配置类信息,将配置类配置的路径下的所有普 通类扫描成BeanDefinition。
  4. 事件和监听的发布处理。
  5. 创建单例池,创建非懒加载的单例bean放入到单例池当中。

prepareRefresh() 方法

  1. protected void prepareRefresh() {
  2. // Switch to active.
  3. //记录启动时间
  4. this.startupDate = System.currentTimeMillis();
  5. // 设置当前容器为激活状态
  6. this.closed.set(false);
  7. this.active.set(true);
  8. if (logger.isDebugEnabled()) {
  9. if (logger.isTraceEnabled()) {
  10. logger.trace("Refreshing " + this);
  11. }
  12. else {
  13. logger.debug("Refreshing " + getDisplayName());
  14. }
  15. }
  16. // Initialize any placeholder property sources in the context environment.
  17. // 初始化property资源文件 Spring没有实现 比如子类可以把ServletContext中的参数对设置到Environment
  18. initPropertySources();
  19. // Validate that all properties marked as required are resolvable:
  20. // see ConfigurablePropertyResolver#setRequiredProperties
  21. // 验证现有的系统资源必须存在哪些资源的key
  22. getEnvironment().validateRequiredProperties();
  23. // Store pre-refresh ApplicationListeners...
  24. // 初始化监听器,如果这个监听器不为空,然后清空监听器
  25. if (this.earlyApplicationListeners == null) {
  26. this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
  27. }
  28. else {
  29. // Reset local application listeners to pre-refresh state.
  30. this.applicationListeners.clear();
  31. this.applicationListeners.addAll(this.earlyApplicationListeners);
  32. }
  33. // Allow for the collection of early ApplicationEvents,
  34. // to be published once the multicaster is available...
  35. this.earlyApplicationEvents = new LinkedHashSet<>();
  36. }

流程总结:

  1. initPropertySources() 在SpringMVC中获取servletContext和servletConfig。
  1. // AbstractRefreshableWebApplicationContext类
  2. protected void initPropertySources() {
  3. ConfigurableEnvironment env = getEnvironment();
  4. if (env instanceof ConfigurableWebEnvironment) {
  5. ((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
  6. }
  7. }
  1. getEnvironment().validateRequiredProperties(); 校验环境中是否存在某个key,可以在任何地方设置,但是环境中必须存在。

obtainFreshBeanFactory() 方法

  1. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  2. // 模版方法刷新BeanFactory
  3. refreshBeanFactory();
  4. return getBeanFactory();
  5. }

流程总结:

  1. 在Spring的实现中AnnotationConfigApplicationContext并没有去实现什么,当你重复调用refresh()它会报错,错误就是在GenericApplicationContext的refreshBeanFactory里面提现出来。
  2. 在另一个AnnotationConfigWebApplicationContext 中支持重复刷新,重复刷新逻辑如下:
  1. protected final void refreshBeanFactory() throws BeansException {
  2. // 是否存在BeanFactory
  3. if (hasBeanFactory()) {
  4. // 销毁bean,关闭BeanFactory,同时会去执行Bean的销毁逻辑
  5. destroyBeans();
  6. closeBeanFactory();
  7. }
  8. try {
  9. // 创建BeanFactory,然后去加载BeanDefinition
  10. DefaultListableBeanFactory beanFactory = createBeanFactory();
  11. beanFactory.setSerializationId(getId());
  12. customizeBeanFactory(beanFactory);
  13. loadBeanDefinitions(beanFactory);
  14. this.beanFactory = beanFactory;
  15. }
  16. catch (IOException ex) {
  17. throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  18. }
  19. }

注: AnnotationConfigApplicationContext在初始化父类去创建BeanFactory,而AnnotationConfigWebApplicationContext是在该方法执行的时候判断然后去生成BeanFactory。

prepareBeanFactory(beanFactory);方法

  1. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  2. // Tell the internal bean factory to use the context's class loader etc.
  3. // 设置类加载器,如果自己设置拿设置的,没有拿默认的
  4. // 由于Spring是通过ASM技术拿到class的全限定名,后面得用类加载器去生成Bean
  5. beanFactory.setBeanClassLoader(getClassLoader());
  6. // Spring5.3中新增的功能,可以选择是否开启Spel功能,shouldIgnoreSpel默认为false,表示开启
  7. if (!shouldIgnoreSpel) {
  8. beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  9. }
  10. // 添加一个ResourceEditorRegistrar,注册一些级别的类型转化器
  11. // String转file,Integer等
  12. beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
  13. // Configure the bean factory with context callbacks.
  14. // 组成一个BeanPostProcessor,用来处理EnvironmentAware、EmbeddedValueResolverAware等回调
  15. // 那么它会在bean的实例化前来调用这些aware的回调方法
  16. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  17. // 如果一个属性对应的set方法在ignoredDependencyInterfaces接口中被定义了,则该属性不会进行自动注入
  18. //(是Spring中的自动注入,不是@Autowired)
  19. // Spring 依赖注入会扫描所有set方法,但是会排除以下几个ignoreDependencyInterface
  20. beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
  21. beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
  22. beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
  23. beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
  24. beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
  25. beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
  26. beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
  27. // BeanFactory interface not registered as resolvable type in a plain factory.
  28. // MessageSource registered (and found for autowiring) as a bean.
  29. // Spring 将这四个类放到一个map(resolvableDependencies)当中,当我们依赖注入的时候findAutowireCandidates
  30. // spring容器会给你直接从resolvableDependencies中找到然后直接给你注入
  31. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  32. beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  33. beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  34. beanFactory.registerResolvableDependency(ApplicationContext.class, this);
  35. // Register early post-processor for detecting inner beans as ApplicationListeners.
  36. // ApplicationListenerDetector负责把ApplicantsListener类型的Bean注册到ApplicationContext中
  37. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
  38. // Detect a LoadTimeWeaver and prepare for weaving, if found.
  39. // Aspectj本身是通过编译期进行代理的,在Spring中就跟LoadTimeWeaver有关
  40. if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
  41. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
  42. // Set a temporary ClassLoader for type matching.
  43. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  44. }
  45. // Register default environment beans.
  46. // 将environment直接注册成一个单例bean,environment是系统的环境变量信息
  47. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
  48. beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  49. }
  50. // 将系统中的属性配置信息注册一个bean,bean的名字就是systemProperties
  51. if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
  52. beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
  53. }
  54. // 将系统的环境变量注册成一个单例bean,systemEnvironment
  55. if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
  56. beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
  57. }
  58. // 将监控对象注册成一个单例Bean
  59. if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
  60. beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
  61. }
  62. }

流程总结:

  1. 设置类加载器。
  2. 注入一些解析器和转换器 StandardBeanExpressionResolver,ResourceEditorRegistrar。
  3. 注入Aware回调类,排除依赖注入相关类。
  4. 初始化相关对象BeanFactory,ResourceLoader,ApplicationEventPublisher,ApplicationContext。
  5. 注入环境变量的相关Bean

invokeBeanFactoryPostProcessors(beanFactory);方法

  1. public static void invokeBeanFactoryPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
  3. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  4. Set<String> processedBeans = new HashSet<>();
  5. if (beanFactory instanceof BeanDefinitionRegistry) {
  6. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  7. List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
  8. List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
  9. // beanFactoryPostProcessors集合一般情况下都是空的,除非我们手动调用容器的addBeanFactoryPostProcessor方法添加了
  10. // beanFactoryPostProcessors中可能包含了:普通BeanFactoryPostProcessor对象和BeanDefinitionRegistryPostProcessor对象
  11. // 对于BeanDefinitionRegistryPostProcessor对象,会执行自己的postProcessBeanDefinitionRegistry()方法
  12. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
  13. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
  14. BeanDefinitionRegistryPostProcessor registryProcessor =
  15. (BeanDefinitionRegistryPostProcessor) postProcessor;
  16. registryProcessor.postProcessBeanDefinitionRegistry(registry);
  17. registryProcessors.add(registryProcessor);
  18. }
  19. else {
  20. regularPostProcessors.add(postProcessor);
  21. }
  22. }
  23. // Do not initialize FactoryBeans here: We need to leave all regular beans
  24. // uninitialized to let the bean factory post-processors apply to them!
  25. // Separate between BeanDefinitionRegistryPostProcessors that implement
  26. // PriorityOrdered, Ordered, and the rest.
  27. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
  28. // 执行扫描出来的BeanDefinitionRegistryPostProcessor
  29. // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
  30. String[] postProcessorNames =
  31. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  32. for (String ppName : postProcessorNames) {
  33. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  34. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  35. processedBeans.add(ppName);
  36. }
  37. }
  38. // 升序排序
  39. sortPostProcessors(currentRegistryProcessors, beanFactory);
  40. registryProcessors.addAll(currentRegistryProcessors);
  41. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  42. currentRegistryProcessors.clear();
  43. // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  44. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  45. for (String ppName : postProcessorNames) {
  46. // processedBeans表示该beanFactoryPostProcessor的postProcessBeanDefinitionRegistry()方法已经执行过了,不再重复执行
  47. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
  48. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  49. processedBeans.add(ppName);
  50. }
  51. }
  52. sortPostProcessors(currentRegistryProcessors, beanFactory);
  53. registryProcessors.addAll(currentRegistryProcessors);
  54. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  55. currentRegistryProcessors.clear();
  56. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  57. // 执行哪些没有实现了PriorityOrdered或Ordered接口的普通BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
  58. // 在这个过程中可能会向BeanFactory中注册另外的BeanDefinitionRegistryPostProcessor,所以需要while,直到确定所有的BeanDefinitionRegistryPostProcessor都执行完了
  59. // 在这个过程中注册的BeanDefinitionRegistryPostProcessor,所实现的PriorityOrdered或Ordered接口可能会不按顺序执行
  60. // 比如 A注册了B和C,B又注册了D和E,那么B和C会按顺序执行,D和E也会按顺序执行,但是B、C、D、E整体不能保证是顺序执行
  61. boolean reiterate = true;
  62. while (reiterate) {
  63. reiterate = false;
  64. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  65. for (String ppName : postProcessorNames) {
  66. if (!processedBeans.contains(ppName)) {
  67. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  68. processedBeans.add(ppName);
  69. reiterate = true;
  70. }
  71. }
  72. sortPostProcessors(currentRegistryProcessors, beanFactory);
  73. registryProcessors.addAll(currentRegistryProcessors);
  74. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
  75. currentRegistryProcessors.clear();
  76. }
  77. // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
  78. // 执行完BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法后,
  79. // 再执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法
  80. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  81. // 执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法
  82. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  83. }
  84. else {
  85. // Invoke factory processors registered with the context instance.
  86. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  87. }
  88. // 执行扫描出来的普通BeanFactoryPostProcessor
  89. // Do not initialize FactoryBeans here: We need to leave all regular beans
  90. // uninitialized to let the bean factory post-processors apply to them!
  91. String[] postProcessorNames =
  92. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  93. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  94. // Ordered, and the rest.
  95. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  96. List<String> orderedPostProcessorNames = new ArrayList<>();
  97. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  98. // 先进行分类
  99. for (String ppName : postProcessorNames) {
  100. if (processedBeans.contains(ppName)) {
  101. // skip - already processed in first phase above
  102. }
  103. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  104. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  105. }
  106. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  107. orderedPostProcessorNames.add(ppName);
  108. }
  109. else {
  110. nonOrderedPostProcessorNames.add(ppName);
  111. }
  112. }
  113. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  114. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  115. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  116. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  117. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  118. for (String postProcessorName : orderedPostProcessorNames) {
  119. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  120. }
  121. sortPostProcessors(orderedPostProcessors, beanFactory);
  122. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  123. // Finally, invoke all other BeanFactoryPostProcessors.
  124. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  125. for (String postProcessorName : nonOrderedPostProcessorNames) {
  126. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  127. }
  128. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
  129. // Clear cached merged bean definitions since the post-processors might have
  130. // modified the original metadata, e.g. replacing placeholders in values...
  131. beanFactory.clearMetadataCache();
  132. }

流程总结:

registerBeanPostProcessors(beanFactory);方法

  1. public static void registerBeanPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
  3. // 拿到所有的BeanPostProcessor
  4. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
  5. // Register BeanPostProcessorChecker that logs an info message when
  6. // a bean is created during BeanPostProcessor instantiation, i.e. when
  7. // a bean is not eligible for getting processed by all BeanPostProcessors.
  8. // beanProcessorTargetCount表示BeanFactory中所有的BeanPostProcessor数量,+1表示BeanPostProcessorChecker
  9. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
  10. beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
  11. // Separate between BeanPostProcessors that implement PriorityOrdered,
  12. // Ordered, and the rest.
  13. List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  14. List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
  15. List<String> orderedPostProcessorNames = new ArrayList<>();
  16. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  17. for (String ppName : postProcessorNames) {
  18. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  19. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  20. priorityOrderedPostProcessors.add(pp);
  21. if (pp instanceof MergedBeanDefinitionPostProcessor) {
  22. internalPostProcessors.add(pp);
  23. }
  24. }
  25. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  26. orderedPostProcessorNames.add(ppName);
  27. }
  28. else {
  29. nonOrderedPostProcessorNames.add(ppName);
  30. }
  31. }
  32. // First, register the BeanPostProcessors that implement PriorityOrdered.
  33. // 升序排序
  34. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  35. registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
  36. // Next, register the BeanPostProcessors that implement Ordered.
  37. List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  38. for (String ppName : orderedPostProcessorNames) {
  39. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  40. orderedPostProcessors.add(pp);
  41. if (pp instanceof MergedBeanDefinitionPostProcessor) {
  42. internalPostProcessors.add(pp);
  43. }
  44. }
  45. sortPostProcessors(orderedPostProcessors, beanFactory);
  46. registerBeanPostProcessors(beanFactory, orderedPostProcessors);
  47. // Now, register all regular BeanPostProcessors.
  48. List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  49. for (String ppName : nonOrderedPostProcessorNames) {
  50. BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
  51. nonOrderedPostProcessors.add(pp);
  52. if (pp instanceof MergedBeanDefinitionPostProcessor) {
  53. internalPostProcessors.add(pp);
  54. }
  55. }
  56. registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
  57. // Finally, re-register all internal BeanPostProcessors.
  58. // MergedBeanDefinitionPostProcessor排在最后
  59. sortPostProcessors(internalPostProcessors, beanFactory);
  60. registerBeanPostProcessors(beanFactory, internalPostProcessors);
  61. // Re-register post-processor for detecting inner beans as ApplicationListeners,
  62. // moving it to the end of the processor chain (for picking up proxies etc).
  63. // ApplicationListenerDetector放在所有BeanPostProcessor之后,注意ApplicationListenerDetector的equals()方法实现
  64. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
  65. }

流程总结:

  1. 获取所有的BeanPostProcessor,排序注册成Bean
  2. 对于实现MergedBeanDefinitionPostProcessor,我们将所有的都放到最后。

initMessageSource();方法

  1. protected void initMessageSource() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
  4. // 这里是初始化国际化资源信息,在单例池中看是否有一个bean是messageSource,如果有
  5. this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
  6. // Make MessageSource aware of parent MessageSource.
  7. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
  8. HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
  9. if (hms.getParentMessageSource() == null) {
  10. // Only set parent context as parent MessageSource if no parent MessageSource
  11. // registered already.
  12. // 拿父ApplicationContext的messageSource作为this.messageSource的父messageSource
  13. hms.setParentMessageSource(getInternalParentMessageSource());
  14. }
  15. }
  16. if (logger.isTraceEnabled()) {
  17. logger.trace("Using MessageSource [" + this.messageSource + "]");
  18. }
  19. }
  20. else {
  21. // Use empty MessageSource to be able to accept getMessage calls.
  22. DelegatingMessageSource dms = new DelegatingMessageSource();
  23. dms.setParentMessageSource(getInternalParentMessageSource());
  24. this.messageSource = dms;
  25. beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
  26. if (logger.isTraceEnabled()) {
  27. logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
  28. }
  29. }
  30. }

总结流程:

  1. Spring 不是自己完全实现国际化,而是MessageSource去实现。
  2. 判断它是否实现了HierarchicalMessageSource,也就是父类的国际化,如果没有这个bean就创建一个默认的beanmessageSource,类型是DelegatingMessageSource。

自定义MessageSource

  1. public MessageSource messageSource() {
  2. ResourceBundleMessageSource message = new ResourceBundleMessageSource();
  3. message.setBasename("message");
  4. return messageSource;
  5. }

initApplicationEventMulticaster();方法

  1. protected void initApplicationEventMulticaster() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. // 判断是否定义了applicationEventMulticaster事件广播器,如果存在直接赋值。
  4. if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
  5. this.applicationEventMulticaster =
  6. beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
  7. if (logger.isTraceEnabled()) {
  8. logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
  9. }
  10. }
  11. // 如果不存在就默认创建一个SimpleApplicationEventMulticaster 事件广播器
  12. else {
  13. this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
  14. beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
  15. if (logger.isTraceEnabled()) {
  16. logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
  17. "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
  18. }
  19. }
  20. }

流程总结:创建事件广播器,初始化事件的发布器。

registerListeners();方法

  1. protected void registerListeners() {
  2. // Register statically specified listeners first.
  3. // 将所有的监听器添加到事件发布器当中。
  4. for (ApplicationListener<?> listener : getApplicationListeners()) {
  5. getApplicationEventMulticaster().addApplicationListener(listener);
  6. }
  7. // Do not initialize FactoryBeans here: We need to leave all regular beans
  8. // uninitialized to let post-processors apply to them!
  9. // 获取FactoryBean调用getObject方法生成的ApplicationListener,将其添加到事件发布器中。
  10. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  11. for (String listenerBeanName : listenerBeanNames) {
  12. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  13. }
  14. // Publish early application events now that we finally have a multicaster...
  15. // 添加了事件监听器后,判断是否有earlyApplicationEvents,如果有就使用事件广播器发布earlyApplicationEvents
  16. // earlyApplicationEvents表示在事件广播器还没生成好之前ApplicationContext所发布的事件
  17. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  18. this.earlyApplicationEvents = null;
  19. if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
  20. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  21. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  22. }
  23. }
  24. }

事件发布机制的相关类总结:

SimpleApplicationEventMulticaster:默认情况下的事件发布器

ApplicationListenerDetector,EventListenerMethodProcessor,DefaultEventListenerFactory。

如果判断该类为监听类 ApplicationListenerDetector BeanPostProcessor(实现方式)

  1. // 初始化后的方法,来判断是否为ApplicationListener类型
  2. public Object postProcessAfterInitialization(Object bean, String beanName) {
  3. if (bean instanceof ApplicationListener) {
  4. // potentially not detected as a listener by getBeanNamesForType retrieval
  5. Boolean flag = this.singletonNames.get(beanName);
  6. if (Boolean.TRUE.equals(flag)) {
  7. // singleton bean (top-level or inner): register on the fly
  8. this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
  9. }
  10. else if (Boolean.FALSE.equals(flag)) {
  11. if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
  12. // inner bean with other scope - can't reliably process events
  13. logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
  14. "but is not reachable for event multicasting by its containing ApplicationContext " +
  15. "because it does not have singleton scope. Only top-level listener beans are allowed " +
  16. "to be of non-singleton scope.");
  17. }
  18. this.singletonNames.remove(beanName);
  19. }
  20. }
  21. return bean;
  22. }

判断方法是监听方法:EventListenerMethodProcessor ,DefaultEventListenerFactory(注解)

  1. public void afterSingletonsInstantiated() {
  2. ConfigurableListableBeanFactory beanFactory = this.beanFactory;
  3. Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set");
  4. String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
  5. for (String beanName : beanNames) {
  6. if (!ScopedProxyUtils.isScopedTarget(beanName)) {
  7. // 拿到当前Bean对象的类型
  8. Class<?> type = null;
  9. try {
  10. type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
  11. }
  12. catch (Throwable ex) {
  13. // An unresolvable bean type, probably from a lazy bean - let's ignore it.
  14. if (logger.isDebugEnabled()) {
  15. logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
  16. }
  17. }
  18. if (type != null) {
  19. if (ScopedObject.class.isAssignableFrom(type)) {
  20. try {
  21. Class<?> targetClass = AutoProxyUtils.determineTargetClass(
  22. beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));
  23. if (targetClass != null) {
  24. type = targetClass;
  25. }
  26. }
  27. catch (Throwable ex) {
  28. // An invalid scoped proxy arrangement - let's ignore it.
  29. if (logger.isDebugEnabled()) {
  30. logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex);
  31. }
  32. }
  33. }
  34. try {
  35. processBean(beanName, type);
  36. }
  37. catch (Throwable ex) {
  38. throw new BeanInitializationException("Failed to process @EventListener " +
  39. "annotation on bean with name '" + beanName + "'", ex);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. private void processBean(final String beanName, final Class<?> targetType) {
  46. if (!this.nonAnnotatedClasses.contains(targetType) &&
  47. AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
  48. !isSpringContainerClass(targetType)) {
  49. // 找到所有加了@EventListener注解的方法
  50. Map<Method, EventListener> annotatedMethods = null;
  51. try {
  52. annotatedMethods = MethodIntrospector.selectMethods(targetType,
  53. (MethodIntrospector.MetadataLookup<EventListener>) method ->
  54. AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
  55. }
  56. catch (Throwable ex) {
  57. // An unresolvable type in a method signature, probably from a lazy bean - let's ignore it.
  58. if (logger.isDebugEnabled()) {
  59. logger.debug("Could not resolve methods for bean with name '" + beanName + "'", ex);
  60. }
  61. }
  62. if (CollectionUtils.isEmpty(annotatedMethods)) {
  63. this.nonAnnotatedClasses.add(targetType);
  64. if (logger.isTraceEnabled()) {
  65. logger.trace("No @EventListener annotations found on bean class: " + targetType.getName());
  66. }
  67. }
  68. else {
  69. // Non-empty set of methods
  70. ConfigurableApplicationContext context = this.applicationContext;
  71. Assert.state(context != null, "No ApplicationContext set");
  72. List<EventListenerFactory> factories = this.eventListenerFactories;
  73. Assert.state(factories != null, "EventListenerFactory List not initialized");
  74. for (Method method : annotatedMethods.keySet()) {
  75. for (EventListenerFactory factory : factories) {
  76. // 利用EventListenerFactory来对加了@EventListener注解的方法生成ApplicationListener对象
  77. if (factory.supportsMethod(method)) {
  78. Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
  79. ApplicationListener<?> applicationListener =
  80. factory.createApplicationListener(beanName, targetType, methodToUse);
  81. if (applicationListener instanceof ApplicationListenerMethodAdapter) {
  82. ((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
  83. }
  84. context.addApplicationListener(applicationListener);
  85. break;
  86. }
  87. }
  88. }
  89. if (logger.isDebugEnabled()) {
  90. logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" +
  91. beanName + "': " + annotatedMethods);
  92. }
  93. }
  94. }
  95. }

流程总结:

  1. 无论是懒加载还是非懒加载的bean都会被加入到Spring中,因为在发布时间的时候他会主动的再去获取一下容器里面的所有的ApplicationListener类,但是使用注解来定义方法在方法上写@Lazy注解该监听器不会生效。
  2. 广播模式默认情况下是串行去执行,也支持去设置一个线程池异步执行。

finishBeanFactoryInitialization(beanFactory);方法

  1. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  2. // Initialize conversion service for this context.
  3. // 如果BeanFactory中存在名字叫conversionService的Bean,则设置到BeanFactory中
  4. // ConversionService是用来进行类型转换的
  5. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  6. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  7. beanFactory.setConversionService(
  8. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  9. }
  10. // Register a default embedded value resolver if no BeanFactoryPostProcessor
  11. // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
  12. // at this point, primarily for resolution in annotation attribute values.
  13. // 设置默认的占位符解析器,使用environment去解析占位符
  14. if (!beanFactory.hasEmbeddedValueResolver()) {
  15. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  16. }
  17. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  18. // 加载时植入
  19. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  20. for (String weaverAwareName : weaverAwareNames) {
  21. getBean(weaverAwareName);
  22. }
  23. // Stop using the temporary ClassLoader for type matching.
  24. beanFactory.setTempClassLoader(null);
  25. // Allow for caching all bean definition metadata, not expecting further changes.
  26. beanFactory.freezeConfiguration();
  27. // Instantiate all remaining (non-lazy-init) singletons.
  28. // 初始化非懒加载的单例Bean
  29. beanFactory.preInstantiateSingletons();
  30. }

流程总结:

  1. 初始化非懒加载的单例Bean。
  2. 进行Bean的相关生命周期。

finishRefresh();方法

  1. protected void finishRefresh() {
  2. // Clear context-level resource caches (such as ASM metadata from scanning).
  3. clearResourceCaches();
  4. // Initialize lifecycle processor for this context.
  5. // 设置lifecycleProcessor,默认为DefaultLifecycleProcessor
  6. // 初始化容器的上下文生命周期
  7. // 容器启动完成后会去调start方法,停止会去调stop方法(但是必须isRunning返回true
  8. initLifecycleProcessor();
  9. // Propagate refresh to lifecycle processor first.
  10. // 调用LifecycleBean的start()
  11. getLifecycleProcessor().onRefresh();
  12. // Publish the final event.
  13. // 发布容器刷新完所有事件
  14. publishEvent(new ContextRefreshedEvent(this));
  15. // Participate in LiveBeansView MBean, if active.
  16. if (!NativeDetector.inNativeImage()) {
  17. LiveBeansView.registerApplicationContext(this);
  18. }
  19. }

流程总结:

  1. 监听Spring容器生命周期,实现SmartLifeCycle。
  2. 发布所有监听的事件。

至此整个Spring容器就启动完成。

更多详情请关注---Java从零到壹

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/609325
推荐阅读
相关标签
  

闽ICP备14008679号