前言:控制反转(Inversion of Control,英文缩写为IoC)是一个重要的面向对象编程的法则来削减计算机程序的耦合问题,也是轻量级的Spring框架的核心。 控制反转一般分为两种类型,依赖注入(Dependency Injection,简称DI)和依赖查找(Dependency Lookup)。依赖注入应用比较广泛。
1.新建项目project ,命名Spring1002
2.com.java.service
JavaWork.java代码:
1 package com.java.service; 2 3 public class JavaWork { 4 //相当于实体类 5 public Tester tester; 6 7 public void setTester(Tester tester) { 8 this.tester = tester; 9 } 10 public void doTest(){ 11 tester.test(); 12 } 13 }
Tester.java
package com.java.service; public interface Tester { public void test(); }
ZahngSan.java
package com.java.service; public class ZhangSan implements Tester{ public void test(){ System.out.println("张三————测试程序"); } }
3.com.java.test
Test2.java代码:
package com.java.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.java.service.JavaWork; public class Test2 { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml"); JavaWork javawork=(JavaWork) ac.getBean("javaWork"); javawork.doTest(); } }
4.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.java.service.ZhangSan"></bean> <bean id="javaWork" class="com.java.service.JavaWork"> <property name="tester" ref="zhangsan"></property> </bean> </beans>
运行结果: