Spring简介:IoC与IoC容器

Spring简介:IoC与IoC容器

学习Spring,最主要的就是Spring的两大特性,控制反转(Inversion of Control,IoC)与面向切面/方面编程(Aspect-Oriented Programming,AOP)。

这篇博客主要聊聊IoC。

控制反转(IoC)

首先来看一下官方文档对IoC的解读。

引用自Spring官方文档 →官方文档链接←

IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes or a mechanism such as the Service Locator pattern.

总结下IoC的定义

控制反转(IoC)又被叫做依赖注入(DI)。其实这个是有争议的,有些人认为依赖注入只是控制反转的一种实现。

依赖注入(或者是传递)有以下三种方式:
1. 构造器的参数注入
2. 工厂方法的参数注入
3. 对象实例化(通过构造器或工厂方法)后,使用setter方法注入

被叫做控制反转的原因:依赖注入从根本上反转了对象自己控制实例化和处理依赖,这些操作全部交给IoC容器,而不是类自己本身。

一个对象与其他对象之间的依赖关系,如果不适用控制反转(不交给容器托管),依赖的处理往往是在这个对象创建的时候,也就是由这个对象自己处理依赖关系;使用了控制反转,这个对象的创建与依赖关系的处理,全部交给容器,实现了控制反转

bean

引用自Spring官方文档
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

简答来说,每一个bean都是一个对象。
这些bean对象被IoC容器管理,每一个bean都是由IoC容器实例化与组装(组装也就是依赖的注入)。

IoC容器通过使用元数据(metadata)来实例化bean以及处理bean之间的依赖。

元数据(metadata)

引用自Spring官方文档
The Spring IoC container consumes a form of configuration metadata. This configuration metadata represents how you, as an application developer, tell the Spring container to instantiate, configure, and assemble the objects in your application.

元数据就是某种形式的配置,用来告诉容器怎样实例化bean以及怎样聚合bean。

元数据的形式:

  1. XML文件
  2. Java注解
  3. java代码

IoC容器

The org.springframework.context.ApplicationContext interface represents the Spring IoC container.
The following diagram shows a high-level view of how Spring works. Your application classes are combined with configuration metadata so that, after the ApplicationContext is created and initialized, you have a fully configured and executable system or application.

                                                

org.springframework.context.ApplicationContext接口,用来描述IoC容器。如图所示,字节码文件和元数据文件被容器读取,根据元数据进行创建bean和初始化bean。之后,就可以得到一个完全配置好的系统。

发布了213 篇原创文章 · 获赞 116 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq2071114140/article/details/104155952