依赖注入 Dependency Injection

依赖注入的机制是依赖注入容器接管对象的创建工作,并将该对象的引用注入到需要该对象的组件中。

该例子中,有两个组件 A 和 B,A 依赖于 B。依赖注入容器会分别创建对象 A 和对象 B,将对象 B 注入到对象 A 中。

public class A {
  public void importantMethod() {
    B b = ... ;  // 获取 B 的实例对象
    b.usefulMethod();
    ...
  }
  ...
}

为了能够使容器能够进行依赖注入,需要编写特定的构建方法或者 set 方法。

public class A {
  private B b;
  public void importantMethod() {
    b.usefulMethod();
    ...
  }
  public void setB(B b) {  // set 方法。容器调用该方法,从而注入一个 B 的实例对象。
    this.b = b;
  }
}
//////////////////////////////////////////////
public class A {
  private B b;
  public A(B b) {  // 构造方法。Spring 会先创建 B 的实例,再创建实例 A,然后把 B 注入到实例 A 中。
    this.b = b
  }
  public void importantMethod() {
    b.usefulMethod();
    ...
  }
}

Spring 管理的对象称为 beans。

从 1.0 版本开始,Spring 就同时支持 setter 和构造器方式的依赖注入。

从 2.5 版本开始,通过 Autowired 注解,Spring 支持基于 field 方式的依赖注入,但是缺点是程序必须引入 org.springframework.beans.factory.annotation.Autowired,这会对 Spring 产生依赖,使得程序不能直接迁移到另一个依赖注入容器中。

使用 Spring,程序几乎将所有重要对象的创建工作都移交给了 Spring,并配置如何注入依赖。

Spring 支持两种配置方式:XML(spring-config.xml)和 注解。此外还需要创建一个 ApplicationContext 对象,代表一个 Spring 控制反转容器。

org.springframework.context.ApplicationContext 接口有多个实现,包括 ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext。这两个实现都需要只要一个包含 bean 信息的 XML 文件。

ClassPathXmlApplicationContext  // 在类的加载路径中加载配置文件
FileSystemXmlApplicationContext  // 从文件系统中加载配置文件

下面的例子是从类加载路径中加载 config1.xml 和 config2.xml 的 ApplicationContext 的实例

ApplicationContext context = new ClassPathXmlApplicaitonContext ( new String[] {"config1.xml", "config2.xml" });  // 
Product product = context.getBean("product", "Product.class");  // 获取对象,该 bean 对象的 id 为 product , 类型为 Product, 

 

posted on 2018-11-11 19:03  0820LL  阅读(118)  评论(0编辑  收藏  举报

导航