控制反转IoC(Inversion of Control)是一种设计思想,而DI(依赖注入)是实现IoC的一种方法。在没有使用IOC的程序中,对象间的依赖关系是靠硬编码的方式实现的。引入IOC后对象的创建由程序自己控制的,控制反转即将对象的创建交给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
/**人*/ public abstract class Person { public String name; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/**学生*/ public class Student extends Person { /**身高*/ public int height; /**有参构造方法*/ public Student(String name,int height){ this.name=name; this.height=height; } @Override public String toString() { return "Student{" + "height=" + height+",name="+name +'}'; } }
1 2 3 4 5 6 7 8 9 10 11
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class School { public static void main(String[] args) { //IoC容器 ApplicationContext ctx=new ClassPathXmlApplicationContext("beans02.xml"); //从容器中获取对象 Person tom=ctx.getBean("tom",Person.class); System.out.println(tom); } }
package spring02; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class School { public static void main(String[] args) { //IoC容器 ApplicationContext ctx=new ClassPathXmlApplicationContext("bookbean01.xml","beans02.xml"); //从容器中获取对象 Person tom=ctx.getBean("tom",Person.class); Person rose=ctx.getBean("rose",Person.class); //Address zhuhai=ctx.getBean("zhuhai",Address.class); System.out.println(tom); System.out.println(rose); } }
2.4 scope属性控制从容器中取回对象的作用域
从容器中取回的对象默认是单例的
1 2 3 4 5
Person roseA=ctx.getBean("rose",Person.class); Person roseB=ctx.getBean("rose",Person.class); //Address zhuhai=ctx.getBean("zhuhai",Address.class); System.out.println(tom); System.out.println(roseA==roseB);
//从容器中获取对象 Person tom=ctx.getBean("tom",Person.class); Person roseA=ctx.getBean("rose",Person.class); Person roseB=ctx.getBean("rose",Person.class); //Address zhuhai=ctx.getBean("zhuhai",Address.class); System.out.println(tom); System.out.println(roseA==roseB);