IOC:控制反转
IOC:又称作依赖注入,是一种重要的面向对象编程的法则来削弱计算机程序的耦合问题,也是轻量级框架spring的核心。
代码实现
1.编写Zhangsan、Lisi和接口Tester
package com.newbeedaly.service;
public interface Tester {
public void test();
}
package com.newbeedaly.service;
public class ZhangSan implements Tester{
public void test(){
System.out.println("张三-测试程序");
}
}
package com.newbeedaly.service;
public class Lisi implements Tester{
public void test(){
System.out.println("李四-测试程序");
}
}
2.编写类JavaWork
package com.newbeedaly.service;
public class JavaWork {
// 测试人
private Tester tester;
public void setTester(Tester tester) {
this.tester = tester;
}
public void doTest(){
tester.test();
}
}
3.配置Beans.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="zhangsan" class="com.newbeedaly.service.ZhangSan"></bean>
<bean id="lisi" class="com.newbeedaly.service.Lisi"></bean>
<bean id="javaWork" class="com.newbeedaly.service.JavaWork">
<property name="tester" ref="lisi"></property>
</bean>
</beans>
4.编写Test测试类
package com.newbeedaly.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.newbeedaly.service.JavaWork;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
JavaWork javaWork=(JavaWork)ac.getBean("javaWork");
javaWork.doTest();
}
}