您的位置:首页 > 编程语言 > Java开发

Spring核心(二)IoC介绍

2012-06-13 16:35 435 查看
IoC控制反转模式(也称作依赖性注入DI)是Spring的核心,他的基本概念是:不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。Spring中的IoC容器负责将这些联系在一起。在典型的 IOC 场景中,容器创建了所有对象,并设置必要的属性将它们连接在一起,由容器来决定什么时间调用方法。  
控制反转(loc):控制权的转移。
通过例子来理解一下:
假如我要回家,Dao层可以选择多种方法

[java]
view plaincopyprint?

Public class ByBus{
Public void gohome(){
System.out.println(“坐公交车”);
}
}

[java]
view plaincopyprint?

Public   class  Cycle{
Public  void  gohome(){

System.out.println(“骑自行车”);
}
}

Public   class  Cycle{
Public  void  gohome(){
System.out.println(“骑自行车”);
}
}


业务层,如果选择坐车,那么:

[java]
view plaincopyprint?

Public class GoWhere{
Public void Gohome(){

ByBus byBus=new ByBus();
byBus.gohome();
}
}

[java]
view plaincopyprint?

Public  interface  Ivehicle{
Public  void  gohome();
}

Public  interface  Ivehicle{
Public  void  gohome();
}


然后ByBus和Cycle类都实现Ivehicle接口,在此就省略不贴代码了。
下面是重新设计GoWhere类,回家的方法可设计为依赖Ivehicle接口,而不依赖于实际的ByBus和Cycle。

[java]
view plaincopyprint?

Public class GoWhere{
Private Ivehicle vehicle;
Public void setVehicle(Ivehicle vehicle){
This.vehicle=vehicle;
}
Public void Gohome(){

Vehicle.gohome();
}
}

[java]
view plaincopyprint?

GoWhere  goWhere=new  goWhere();
goWhere.setVehicle(new  ByBus);

goWhere.Gohome();

GoWhere  goWhere=new  goWhere();
goWhere.setVehicle(new  ByBus);
goWhere.Gohome();


如果选择骑车回家,则写为:

[java]
view plaincopyprint?

GoWhere goWhere=new goWhere();
goWhere.setVehicle(new Cycle);

goWhere.Gohome();

GoWhere goWhere=new goWhere();
goWhere.setVehicle(new Cycle);
goWhere.Gohome();

由此可以看出,无论底层的存储如何变化,对于GoWhere类来说都不用修改。修改的只是客户端。
我们可以编写一个配置文件,在配置文件中对所需的对象进行配置,这样的话,连客户端的代码都不用修改,就可以方便的更换方法。
其实,Spring的核心容器IOC就是提供的这样对象的配置管理功能。

Spring中IOC的基本概念是:基于OO设计原则的TheHollywood Principle:Don’t call us, we’ll call you(别找我,我会来找你的)。程序中各个组件之间的关系,不由程序代码直接操控,而由容器控制。控制权由应用代码中转到了外部容器,即所谓的反转。也就是说对象的控制权转交给spring容器。
下篇文章介绍Spring中IOC的使用方法,看看上文中的例子用Spring管理后会有什么变化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: