↓ Skip to main content
  1. Posts/

spring 依赖注入

·621 words·2 mins
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

真是个不明觉厉的术语…其实是个特别简单的概念orz

用白话讲,如果一个class A中用到了class B的实例,那么class B的实例就是class A的依赖,如果不是在class A中定义class B的实例,而是通过某个接口,将class B的实例传入class A,就叫依赖注入。

 1public class Example {
 2 // private DatabaseThingie myDatabase;
 3
 4 // public Example() {
 5 //   myDatabase = new DatabaseThingie();
 6 // }
 7
 8  public Example(DatabaseThingie useThisDatabaseInstead) {
 9    myDatabase = useThisDatabaseInstead;
10  }
11
12  public void DoStuff() {
13    ...
14    myDatabase.GetData();
15    ...
16  }
17}

依赖注入(DI)和控制反转(IOC)基本是一个意思,因为说起来谁都离不开谁。

简单来说,a依赖b,但a不控制b的创建和销毁,仅使用b,那么b的控制权交给a之外处理,这叫控制反转(IOC),而a要依赖b,必然要使用b的instance,那么

  1. 通过a的接口,把b传入;
  2. 通过a的构造,把b传入;
  3. 通过设置a的属性,把b传入;

这个过程叫依赖注入(DI)。

那么什么是IOC Container?

随着DI的频繁使用,要实现IOC,会有很多重复代码,甚至随着技术的发展,有更多新的实现方法和方案,那么有人就把这些实现IOC的代码打包成组件或框架,来避免人们重复造轮子。

所以实现IOC的组件或者框架,我们可以叫它IOC Container。

作者:phoenix 链接:https://www.zhihu.com/question/32108444/answer/220819349 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

参考资料:

Dependency Injection Demystified

What is dependency injection?

Related

learn java in 21 minutes for C++ Programmers

·761 words·2 mins
先放资料: Learning a New Programming Language: Java for C++ Programmers java package # 先说几条重要的人话: 一个 java 文件第一行可以声明该文件所属于的 package,package 的名字必须与整个工作目录的路径名相同。 同一个 package 下的 class 默认有互相访问的权限。 访问属性设置为 public 的 class,如果该 class 所在的 file 声明了 package,那么可以被其他 package 下的 class 访问到。 .java 的文件名必须与文件中设置为 public 的 class 名保持一致(如果没有 public 的类,那么名称任意)。 Every class is part of some package. All classes in a file are part of the same package. You can specify the package using a package declaration (package name;) as the first (non-comment) line in the file. Multiple files can specify the same package name. If no package is specified, the classes in the file go into a special unnamed package (the same unnamed package for all files). If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name). You can access public classes in another (named) package using package-name.class-name. You can access the public fields and methods of such classes using package-name.class-name.field-or-method-name. You can avoid having to include the package-name using import package-name.*; or import package-name.class-name; at the beginning of the file (after the package declaration). The former imports all of the classes in the package, and the second imports just the named class. You must still use class-name to access the classes in the packages, and class-name.field-or-method-name to access the fields and methods of the class; the only thing you can leave off is the package name. 下面是一些例子: