IOC细解+示例

来源:互联网 发布:sdn会取代那些传统网络 编辑:程序博客网 时间:2024/06/13 07:20

本博客是读spring 3.x企业应用开发实战后按自己理解写的(博文是个人理解):

ioc的目的就是让多个对象间解耦,如:A 要调用B中两个变量的和,


public class A{

private int a;

B b = new B();

a = b.add();

}


public clas B{

private int i,j;

public  int add(){

    return i+j;

}

}

那么当要修改B的时候,那么A中的代码也要修改,所以A,B没有解耦。

下面就通过属性注入的方式来进行解耦(属性注入是ioc解耦其中一种也是最常用的一种,还有构造函数注入和接口注入,本博文不一 一举例):

我们可以通过类C进行A和B的解耦:

public class A{

private int  a;

private void setA(Class <?> D){

thisa.a =  D;

}

}

public  class C{

public viod mocth(){

Class <?> B = new D();     //D代表要传值给a的类

A aclass = new A();

aclass.setA(D);

}

}

通过C使A和B脱离关系,C在spring中是容器。