Spring学习02——控制反转、依赖注入
有两个人,张三和李四
package com.su.service; public class ZhangSan implements Tester{ public void test(){ System.out.println("张三-测试程序"); } }
package com.su.service; public class Lisi implements Tester{ public void test(){ System.out.println("李四-测试程序"); } }
有一个Tester接口,张三和李四都实现了这个接口
package com.su.service; public interface Tester { public void test(); }
测试工作类
package com.su.service; public class JavaWork { private Tester tester; public void setTester(Tester tester) { this.tester = tester; } public void doTest(){ // ZhangSan zhangsan=new ZhangSan(); // zhangsan.test(); tester.test(); } }
主管负责分配谁去测试(通过setTester,即控制权交给主管,而非每次换人去测试,都要在JavaWork的doTest类中new出人,这就是控制反转)
package com.su.test; import com.su.service.JavaWork; import com.su.service.Lisi; public class Test { /** * 主管执行命令 */ public static void main(String[] args) { JavaWork javaWork=new JavaWork(); // javaWork.setTester(new ZhangSan()); javaWork.setTester(new Lisi()); javaWork.doTest(); } }
而spring帮助我们做的就是这个,在xml文件中通过配置(spring管理bean),分配测试人员
<?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.su.service.ZhangSan"></bean> <bean id="lisi" class="com.su.service.Lisi"></bean> <bean id="javaWork" class="com.su.service.JavaWork"> <property name="tester" ref="lisi"></property> </bean> </beans>
package com.su.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.su.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(); } }