目录
前言
这是因特奈特上面不知道第几万篇讲依赖注入(Dependency Injection)的文章,但是说明白的却寥寥无几,这篇文章尝试控制字数同时不做大多数。
首先,依赖注入的是一件很简单的事情。
为什么需要依赖注入
然后,假设我们有一个汽车Car,一个引擎接口Engine,两个引擎具体实现Level4Engine,Level5Engine。汽车可以长这样:
public class Car{ private Engine e; public Car(){ e = new Level4Engine(); } public void ignite(){ System.out.println() } }现在要让汽车点火,简单:
public static void main(String[] args) { Car c = new Car(); c.ignite(); }但是假如我们想要换一个更高级的引擎,我们不得不修改Car的构造函数:
~~ e = new Level4Engine(); ~~e = new Level5Engine();
然后重新编译。这就是代码的耦合,一方面假如需求不会经常改变,这个汽车只会使用Level4Engine,那没问题,这个代码很完美。但另一方面,假如引擎有多个,需求会经常改变,我们发现Level4Engine还不行,需要更高级的,而且新引擎还需要进行一系列复杂配置,那这个耦合就是灾难了。只是装配汽车的血汗工人,懂不了那么多的。
怎么进行依赖注入
依赖注入就是为了解决上述问题而生的。用依赖注入的写法解决上面的问题:
public class Car{ private Engine e; public Car(Engine e){ this.e = e; } public void ignite(){ System.out.println() } } // 也可以使用xml进行配置 @Confignuration public CarFactory{ @Bean
