您的位置:首页 > 其它

IoC与DI

2016-10-19 23:06 281 查看

DI依赖注入

如果在ClassA中,有ClassB的实例,则称ClassA对ClassB有一个依赖。

依赖

public class Human {

...

Father father;

...

public Human() {

father = new Father();

}

}


很显然用这种方式new 依赖的对象,如果需要不同的方式取new的话,需要修改Human中的代码,是很麻烦的。这时就有了依赖注入技术

DI的多种方式

1.构造器注入

public class Human {

...

Father father;

...

public Human(Father father) {

this,father = father;

}

}


2.Setter方法注入

public class Human {

...

Father father;

...

public void setFather(Father father) {

this,father = father;

}

}


3.接口注入

interface FatherInstanceInterface {

public void setFather(Father father);

}

public class Human implements FatherInstanceInterface{

...

Father father;

...

public void setFather(Father father) {

this,father = father;

}

}


接口注入和setter方法注入类似,不同的是接口注入使用了统一的方法来完成注入,而setter方法注入的方法名称相对比较随意。

4.注解注入

public class Human implements FatherInstanceInterface{

...

@xxxxx

Father father;

...

}


通过专们的容器对注解扫描,再进行注入

IoC控制反转

是一种设计原则,用来减低耦合度。通过控制反转,对象在被创建的时候,依赖被注入到对象中。

DI是IoC的方式

控制反转是一种思想

依赖注入是一种设计模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ioc di 依赖注入