Spring IOC源码:实例化前的准备工作

简介: Spring IOC源码:实例化前的准备工作

文章目录

Spring源码系列:

Spring IOC源码:简单易懂的Spring IOC 思路介绍

Spring IOC源码:核心流程介绍

Spring IOC源码:ApplicationContext刷新前准备工作

Spring IOC源码:obtainFreshBeanFactory 详解(上)

Spring IOC源码:obtainFreshBeanFactory 详解(中)

Spring IOC源码:obtainFreshBeanFactory 详解(下)

Spring IOC源码:<context:component-scan>源码详解

Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解

Spring IOC源码:registerBeanPostProcessors 详解

Spring IOC源码:实例化前的准备工作

Spring IOC源码:finishBeanFactoryInitialization详解

Spring IoC源码:getBean 详解

Spring IoC源码:createBean( 上)

Spring IoC源码:createBean( 中)

Spring IoC源码:createBean( 下)

Spring IoC源码:finishRefresh 完成刷新详解

前言

上篇文章我们讲解了IOC比较重要的后置处理器注册方法,本篇文章讲解实例化前的准备工作,包括国际化、多播器创建、监听器注册等节点。

正文

进入refresh方法中,可以看到在正式实例化初始化方法前,还有4个方法:

1、initMessageSource();

这个方法主要作用就是使用国际化,定制不同的消息文本,比如定义了一个Person的Bean,它有name属性,我们需要在不同的国家展示对应国家所在语言名称,这时候就可以使用国际化了。


2、initApplicationEventMulticaster();

初始化应用事件广播器。这是观察者模式得典型应用。我们知道观察者模式由主题Subject和Observer组成。广播器相当于主题Subject,其包含多个监听器。当主题发生变化时会通知所有的监听器。


3、onRefresh();

onRefresh 是一个为使用者进行扩展的方法,如:springboot。


4、registerListeners();

将内部的、以及我们自定义的监听器添加到缓存中,以及添加事件源到缓存中,为后续逻辑处理做准备。

方法1:initMessageSource

ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //判断工厂中是否存在MessageSource类型的定义信息
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
      //实例化
      this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
      // 设置父类消息解析对象
      if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
        HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
        if (hms.getParentMessageSource() == null) {
          // Only set parent context as parent MessageSource if no parent MessageSource
          // registered already.
          hms.setParentMessageSource(getInternalParentMessageSource());
        }
      }
      if (logger.isTraceEnabled()) {
        logger.trace("Using MessageSource [" + this.messageSource + "]");
      }
    }
    else {
      // 实例化一个空的DelegatingMessageSource 对象
      DelegatingMessageSource dms = new DelegatingMessageSource();
      //设置父类消息解析对象
      dms.setParentMessageSource(getInternalParentMessageSource());
      this.messageSource = dms;
      //注册添加到一级缓存中
      beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
      if (logger.isTraceEnabled()) {
        logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
      }
    }

方法2:initApplicationEventMulticaster

protected void initApplicationEventMulticaster() {
    //获取工厂对象
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //判断工厂中是否有ApplicationEventMulticaster的定义信息
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
    //实例化,为后续实例化环节做准备
      this.applicationEventMulticaster =
          beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      if (logger.isTraceEnabled()) {
        logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
      }
    }
    else {
      //创建一个多播器
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      //添加到一级缓存中
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      if (logger.isTraceEnabled()) {
        logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
            "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
      }
    }
  }

方法3:onRefresh

  protected void onRefresh() throws BeansException {
  }

该方法为拓展接口,供子类实现。

方法4:registerListeners

  protected void registerListeners() {
    // 将上下文中的监听器集合注册到多播器集合中
    for (ApplicationListener<?> listener : getApplicationListeners()) {
      getApplicationEventMulticaster().addApplicationListener(listener);
    }
    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let post-processors apply to them!
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String listenerBeanName : listenerBeanNames) {
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }
    // Publish early application events now that we finally have a multicaster...
    Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
        getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
    }
  }

自定义监听器以及事件源:

事件源:

package service.event;
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent  {
  private static final long serialVersionUID = 2611556444074013268L;
  /**
   * Create a new {@code ApplicationEvent}.
   *
   * @param source the object on which the event initially occurred or with
   *               which the event is associated (never {@code null})
   */
  public MyEvent(Object source) {
    super(source);
  }
}

监听器:

package service.event;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MyListener1 implements ApplicationListener<MyEvent> {
  @Override
  public void onApplicationEvent(MyEvent event) {
    System.out.println("MyListener"+event.toString());
  }
}
package service.event;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MyListener2 implements ApplicationListener<MyEvent> {
  @Override
  public void onApplicationEvent(MyEvent event) {
    System.out.println("MyListener"+event.toString());
  }
}

xml文件配置监听器:

  <bean class="service.event.MyListener1" name="myListener1"></bean>
  <bean class="service.event.MyListener2" name="myListener2"></bean>

入口编写:

  public static void main(String[] args) {
    MyClassPathApplicationContext applicationContext=new MyClassPathApplicationContext("application-scan.xml");
    applicationContext.publishEvent(new MyEvent("猪大肠事件"));
  }

运行结果:

总结

这篇文章内容比较简单,主要是实例化前的准备工作。国际化定制消息类型,初始化多播器,注册监听器,提交发布早期事件。

目录
相关文章
|
1月前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
3月前
|
设计模式 Java 开发者
如何快速上手【Spring AOP】?从动态代理到源码剖析(下篇)
Spring AOP的实现本质上依赖于代理模式这一经典设计模式。代理模式通过引入代理对象作为目标对象的中间层,实现了对目标对象访问的控制与增强,其核心价值在于解耦核心业务逻辑与横切关注点。在框架设计中,这种模式广泛用于实现功能扩展(如远程调用、延迟加载)、行为拦截(如权限校验、异常处理)等场景,为系统提供了更高的灵活性和可维护性。
|
5月前
|
XML 人工智能 Java
Spring IOC 到底是什么?
IOC(控制反转)是一种设计思想,主要用于解耦代码,简化依赖管理。其核心是将对象的创建和管理交给容器处理,而非由程序直接硬编码实现。通过IOC,开发者无需手动new对象,而是由框架负责实例化、装配和管理依赖对象。常见应用如Spring框架中的BeanFactory和ApplicationContext,它们实现了依赖注入和动态管理功能,提升了代码的灵活性与可维护性。
191 1
|
XML Java 数据格式
京东一面:spring ioc容器本质是什么? ioc容器启动的步骤有哪些?
京东一面:spring ioc容器本质是什么? ioc容器启动的步骤有哪些?
|
安全 Java 应用服务中间件
阿里技术官架构使用总结:Spring+MyBatis源码+Tomcat架构解析等
分享Java技术文以及学习经验也有一段时间了,实际上作为程序员,我们都清楚学习的重要性,毕竟时代在发展,互联网之下,稍有一些落后可能就会被淘汰掉,因此我们需要不断去审视自己,通过学习来让自己得到相应的提升。
|
Java 关系型数据库 数据库连接
Spring源码解析--深入Spring事务原理
本文将带领大家领略Spring事务的风采,Spring事务是我们在日常开发中经常会遇到的,也是各种大小面试中的高频题,希望通过本文,能让大家对Spring事务有个深入的了解,无论开发还是面试,都不会让Spring事务成为拦路虎。
311 1
|
Java Spring
Spring底层架构源码解析(三)
Spring底层架构源码解析(三)
509 5
|
XML Java 数据格式
Spring底层架构源码解析(二)
Spring底层架构源码解析(二)
240 4
|
Java Spring 容器
Spring IOC、AOP与事务管理底层原理及源码解析
【10月更文挑战第1天】Spring框架以其强大的控制反转(IOC)和面向切面编程(AOP)功能,成为Java企业级开发中的首选框架。本文将深入探讨Spring IOC和AOP的底层原理,并通过源码解析来揭示其实现机制。同时,我们还将探讨Spring事务管理的核心原理,并给出相应的源码示例。
387 9

热门文章

最新文章

下一篇
oss云网关配置