控制反轉即IoC (Inversion of Control),它把傳統上由程序代碼直接操控的對象的調用權交給容器,經過容器來實現對象組件的裝配和管理。所謂的「控制反轉」概念就是對組件對象控制權的轉移,從程序代碼自己轉移到了外部容器。java
IoC是一個很大的概念,能夠用不一樣的方式來實現。其主要實現方式有兩種:<1>依賴查找(Dependency Lookup):容器提供回調接口和上下文環境給組件。EJB和Apache Avalon都使用這種方式。<2>依賴注入(Dependency Injection):組件不作定位查詢,只提供普通的Java方法讓容器去決定依賴關係。後者是時下最流行的IoC類型,其又有接口注入(Interface Injection),設值注入(Setter Injection)和構造子注入(Constructor Injection)三種方式。 算法
public class MyBusniessObject{ private DataSource ds; private MyCollaborator myCollaborator; public MyBusnissObject(){ Context ctx = null; try{ ctx = new InitialContext(); ds = (DataSource) ctx.lookup(「java:comp/env/dataSourceName」); myCollaborator = (MyCollaborator) ctx.lookup(「java:comp/env/myCollaboratorName」); } } }
package com.zj.ioc.di; public class Content { public void BusniessContent(){ System.out.println("do business"); } public void AnotherBusniessContent(){ System.out.println("do another business"); } }
MyBusniess類展現了一個業務組件,它的實現須要對象Content的注入。代碼3,代碼4,代碼5,6分別演示構造子注入(Constructor Injection),設值注入(Setter Injection)和接口注入(Interface Injection)三種方式。服務器
package com.zj.ioc.di.ctor; import com.zj.ioc.di.Content; public class MyBusiness { private Content myContent; public MyBusiness(Content content) { myContent = content; } public void doBusiness(){ myContent.BusniessContent(); } public void doAnotherBusiness(){ myContent.AnotherBusniessContent(); } }
代碼4設值注入(Setter Injection) MyBusiness.java框架
package com.zj.ioc.di.set; import com.zj.ioc.di.Content; public class MyBusiness { private Content myContent; public void setContent(Content content) { myContent = content; } public void doBusiness(){ myContent.BusniessContent(); } public void doAnotherBusiness(){ myContent.AnotherBusniessContent(); } }
代碼5 設置注入接口InContent.java spa
package com.zj.ioc.di.iface; import com.zj.ioc.di.Content; public interface InContent { void createContent(Content content); }
package com.zj.ioc.di.iface; import com.zj.ioc.di.Content; public class MyBusiness implements InContent{ private Content myContent; public void createContent(Content content) { myContent = content; } public void doBusniess(){ myContent.BusniessContent(); } public void doAnotherBusniess(){ myContent.AnotherBusniessContent(); } }
public static void main(String[] args) throws Exception{ //get the bean factory BeanFactory factory = getBeanFactory(); MessageRender mr = (MessageRender) factory.getBean(「renderer」); mr.render(); }
而一般對注入對象的配置能夠經過一個xml文件完成。xml
本文出自 「子 孑」 博客,請務必保留此出處http://zhangjunhd.blog.51cto.com/113473/126530對象