所谓Ioc(Inverse Of Control),就是通过容器来控制业务对象之间的依赖关系,而非传统的由代码直接控制,即控制权由应用代码中转到了外部容器,控制权发生了转移。控制权的转移带来的好处就是降低了业务对象之间的依赖程序--松耦合。
下面以一个简单的例子具体阐述
1、新建一个Java Project 目录结构如下:
Car类源码:
package com;
public class Car {
private String brand;
private String color;
private int maxSpeed;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public String toString(){
return "Car:brand-"+brand+" color-"+color+" maxSpeed-"+maxSpeed;
}
}
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-3.2.xsd">
<bean id="car" class="com.Car">
<property name="brand" value="红旗CA72"/>
<property name="color" value="黑色"/>
<property name="maxSpeed" value="200"/>
</bean>
</beans>
Test类源码:
package com;
import java.io.File;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
String path=new File("").getAbsolutePath()+"/src/com/beans.xml";
Resource res=new FileSystemResource(path);
BeanFactory factory=new XmlBeanFactory(res);
Car car=(Car) factory.getBean("car");
System.out.println(car);
}
}
运行Test,输出结果:Car:brand-红旗CA72 color-黑色 maxSpeed-200
1、通过new FileSystemResource(path)来定位Spring配置文件并生成Resource对象;
2、通过new XmlBeanFactory(res)来装载Spring配置信息,并启动IoC容器;
3、通过BeanFactory#getBean(beanName)(此时开始实例化对象并装载)从Ioc容器中获取Bean。