Spring IOC 指南

110 阅读1分钟

Spring IOC 指南

Spring IOC 指南

典型回答

1、IOC(inversion of control),“控制反转”
  • 何为控制反转?

    在传统的程序设计中,应用程序代码通常控制着对象的创建和管理。

    在 IOC 中,控制关系发生了反转。控制权被转移到 Spring 容器中,容器负责创建和管理对象,并在需要的时候将它们注入到应用程序中。

    IOC 只是一种思想和理念,可以有不同的实现方式。

    参考: 控制反转(IOC)

  • 在 Spring 的 IOC 中,对象由 IOC 容器创建并管理,我们只需要在使用的时候从容器中获取就行了。

  • 没有 ioc 时

image-20250331150743505

  • 有了 ioc 后

image-20250331150808460

2、IOC 的优点
  1. 使用者不用关心引用 bean 的实现细节。
  2. 不用为创建多个相同的 bean 导致浪费。
  3. 对于 Bean 的修改,使用方无需感知。
3、Spring IOC

image-20250331150512970

  • ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 直接使用 getBean 获取对象
    Student student123 = context.getBean("student123", Student.class);
    
4、Spring IOC 如何实现?

image-20250331145335125

  1. 创建一个新的 AnnotationConfigApplicationContext,扫描给定包中的 Bean 定义并自动刷新上下文。
  2. 获取指定 Bean 的一个实例。
  3. 调用 Bean 方法。

image-20250331150014087