为什么叫IOC控制反转呢
1、 软件系统在没有引入IoC容器之前,对象A依赖对象B,那么A对象在实例化或者运行到某一点的时候,自己必须主动创建对象B或者使用已经创建好的对象B,其中不管是创建还是使用已创建的对象B,控制权都在我们自己手上。
2、如果软件系统引入了Ioc容器之后,对象A和对象B之间失去了直接联系,所以,当对象A实例化和运行时,如果需要对象B的话,IoC容器会主动创建一个对象B注入到对象A所需要的地方。
3、通过前面的对比,可以看到对象A获得依赖对象B的过程,由主动行为变成了被动行为,即把创建对象交给了IoC容器处理,控制权颠倒过来了,这就是控制反转的由来!
school.java
package ioc.iocsample;
public class School {
private String name;
public School(String name)
{
this.name=name;
}
public void printInfo()
{
System.out.println("school name is:"+name);
}
}
Student.java
package ioc.iocsample;
public class Student {
public int id;
public String name;
private School school;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
}
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="school" class="ioc.iocsample.School">
<constructor-arg index="0">
<value>hello world</value>
</constructor-arg>
</bean>
<bean id="student" class="ioc.iocsample.Student">
<property name="id" value="001"/>
<property name="name" value="王二麻子"/>
<property name="school" ref ="school"/>
</bean>
</beans>
Client.java
package ioc.iocsample;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student=(Student)factory.getBean("student");
student.getSchool().printInfo();
}
}