Spring之IOC

来源:互联网 发布:新浪邮箱端口号 编辑:程序博客网 时间:2024/05/16 01:37

Inversion of Control,就是控制反转的意思,就是说以前对象的创建时交给程序完成,现在交给容器完成。例如,以前Dao是在程序里面创建,并且以前的Dao是用Jdbc完成的,现在想要用Hibernate来完成,那么就得要更改程序代码,现在如果使用ioc,那么我只要修改配置文件即可

 

实例如下:

 

编写一个学生类,学生养了一条狗,

public class Dog{private String name;private String color;public String getName(){return name;}public void setName(String name){this.name = name;}public String getColor(){return color;}public void setColor(String color){this.color = color;}}


 

public class Student{private String name;private int age;private Dog dog;public Dog getDog(){return dog;}public void setDog(Dog dog){this.dog = dog;}public String getName(){return name;}public void setName(String name){this.name = name;}public int getAge(){return age;}public void setAge(int age){this.age = age;}}


在.xml中配置

<bean id="dog" class="com.pojo.Dog" ><property name="name" value="kitty"></property><property name="color" value="yellow"></property></bean><bean id="stu" class="com.pojo.Student" ><property name="name" value="gavin"></property><property name="age" value="21"></property><property name="dog" ref="dog"></property></bean>


在控制器 中调用

ApplicationContext ac=new FileSystemXmlApplicationContext("src/applicationContext.xml");//定义好的一个属性stustu=(Student)ac.getBean("stu");System.out.println("my name is "+stu.getName());System.out.println("my age is "+stu.getAge());System.out.println("my dog 's name is"+stu.getDog().getName());System.out.println("my dog 's color is"+stu.getDog().getColor());

此时创建一个新对象并没有使用new ,而是交给容器创建。这就是控制反转。