以下是来自百度百科对IOC的解释,直接借用了:
所谓IOC的基本概念是:不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。容器负责将这些联系在一起。其原理是基于OO设计原则的The Hollywood Principle:Don't call us, we'll call you(别找我,我会来找你的)。也就是说,所有的组件都是被动的(Passive),所有的组件初始化和调用都由容器负责。组件处在一个容器当中,由容器负责管理。 简单的来讲,就是由容器控制程序之间的关系,而非传统实现中,由程序代码直接操控。这也就是所谓“控制反转”的概念所在:控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。
对于控制反转,共有三种注入方法,分别为接口注入、set注入、构造函数注入。由于接口注入用的较少,所以我只写了后两种注入的简单实现,不多说,直接上代码。
该工程共有四个类、一个接口以及一个xml配置文件,其中TestHelloWorld为测试类,HelloWorld为被注入的类,分别依赖Hello_World和Hello__World类。同时Hello_World和Hello__World都继承接口HelloWorld_Interface。配置文件为config.xml。以下为所有的代码。
package helloWorld;
public interface HelloWorld_Interface {
public String getMsg();
}
package helloWorld;
public class Hello_World implements HelloWorld_Interface{
public String msg = "Hello_World";
public String getMsg(){
return msg;
}
}
package helloWorld;
public class Hello__World implements HelloWorld_Interface{
public String msg = "Hello__World";
public String getMsg(){
return msg;
}
}
package helloWorld; public class HelloWorld { public HelloWorld_Interface hello_World; // public HelloWorld(HelloWorld_Interface hello_World){ // this.hello_World = hello_World; // } public HelloWorld_Interface getHello_World() { return hello_World; } public void setHello_World(HelloWorld_Interface hello_World) { this.hello_World = hello_World; } }
package helloWorld; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class TestHelloWorld { public static void main(String[] args) { //通过ApplicationContext来获取Spring的配置文件 ApplicationContext actx=new FileSystemXmlApplicationContext("config.xml"); HelloWorld HelloWorld = (HelloWorld)actx.getBean("HelloWorld"); System.out.println(HelloWorld.getHello_World().getMsg()); } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!--通过set方法进行注入--> <bean id="Hello_World" class="helloWorld.Hello_World"></bean> <bean id="Hello__World" class="helloWorld.Hello__World"></bean> <bean id = "HelloWorld" class = "helloWorld.HelloWorld"> <property name="hello_World"> <ref bean = "Hello__World"></ref> </property> </bean> <!--通过构造函数进行注入--> <!--<bean id = "Hello_World" class = "helloWorld.Hello_World"></bean>--> <!--<bean id = "Hello__World" class = "helloWorld.Hello__World"></bean>--> <!--<bean id = "HelloWorld" class = "helloWorld.HelloWorld">--> <!--<constructor-arg ref = "Hello__World">--> <!--</constructor-arg>--> <!-- </bean>--> </beans>
另外,需要提醒的是,本次使用的spring框架版本为spring-framework-2.5.5,eclipse版本为3.7.0。使用之前需要将需要的jar包导入eclipse中,包括dist目录下的spring.jar以及lib\jakarta-commons\里面的所有jar包。好了,这样就可以运行了。