Spring Framework series (four) - IOC DI inversion of control and dependency injection

background:

  If the reference object or a dependency management performed by the object-specific coupling of the code will be high, it becomes difficult to code testing. The IOC can solve this problem, put it

These dependencies to the framework or the IOC container management, simplifies the development.

  IOC is a design pattern, and Spring IOC is one of its implementation. Spring IOC JavaBean provide a basic container by the IOC pattern managing dependencies.

IOC (Inversion of Control) two implementations:

  1, DL (Dependency Lookup), has been eliminated, the user needs to find their own resources and assemble objects with invasive

  2, DI (Dependency Injection), responsible for the formation of the assembly

Spring's IOC supported features:

  1, dependency injection

  2, dependency checking

  3, automatic assembly

  4, support the collection

  5, designated initialization methods and methods of destruction

  6, some support callback method (Spring interfaces need to achieve, a slight invasive)

The most important thing is dependency injection, read ref tag from XML, ref is runtimeBeanReference

 

IOC container is divided into two specific forms:

  1, BeanFactory Interface: simple container. Only achieve the most basic functions, can be understood as hashmap, key is BeanName, value is a bean instance

  2, ApplicationContext Interface: advanced container. On the basis of a simple container, a lot of integration interfaces, on behalf of all functions of the entire container. It defines the refresh (), to refresh the entire contents

, A reload / refresh all of the bean

In addition to these two, there are other secondary interface

The higher container relies on low ApplicationContext container getBean (), ClassPathXmlApplicationContext the build process is to initialize the IOC

Process:

1、用户构造ClassPathXmlApplicationContext(简称 CPAC)

  CPAC首先访问了“抽象高级容器”的refresh(),这个方法是模板方法。所以要回调子类(低级容器)的refreshBeanFactory(),作用是使用

低级容器加载所有BeanDefinition和Properties到容器中。

  低级容器加载成功后,高级容器开始处理一些回调,例如Bean后置处理器。回调setBeanFactory法。或者注册监听器等,发布事件,实例化例

Bean等等功能。

简单说就是:

  1、低级容器加载配置文件(从 XML,数据库,Applet),并解析成 BeanDefinition 到低级容器中。

  2、加载成功后,高级容器启动高级功能,例如接口回调,监听器,自动实例化单例,发布事件等等功能。

加载所有的Bean配置成BeanDefinition到容器中,如果Bean有依赖关系,则使用占位符暂时代替。

然后,在调用getBean的时候,进行真正的依赖注入,即如果碰到了属性是ref的(占位符),那么就从容器里获取这个Bean,然后注入到实例中

—— 这就是依赖注入

 

依赖注入方式:

setter、constructor、factory实现

请自行百度或者参考我之前的文章:https://www.cnblogs.com/huigelaile/p/10973913.html

 

想要深入了解可以查看《Spring技术内幕》一书第二章,或者IOC相关源码

内容参考:http://thinkinjava.cn

 

Guess you like

Origin www.cnblogs.com/huigelaile/p/10977931.html