IoC Inverse of Control 反转控制的概念:就是将原本在程序中手动创建HelloService对象的控制权,交由Spring管理,简单来说,就是创建HelloService对象控制权被反转到了Spring框架。
来做个对比:
HelloTest类中使用HelloService类对象
传统方式:
HelloService helloService = new HelloService();
public class HelloService {
private String info ;
public void sayHello() {
System.out.println("你好,"+info);
}
public void setInfo (String info){
this.info = info;
}
}
public class HelloTest {
public static void main(String[] args){
// 这里使用HelloService
HelloService helloService = new HelloService();
helloService.setInfo("北京");
helloService.sayHello();
}
}
* 通常会将业务组件定义为接口
接口的好处:
ArrayList list = new ArrayList();
这样可以利用多态,被其他的子类进行实例化。
list = new ArrayList(); // 数组列表
list = new LinkedList(); // 链表
这样的话,list 和 实现类紧密耦合
要解决紧密耦合 ---- 》 使用工厂模式
List list =(工厂模式)= new ArrayList();
List list = listFactory.getList(); // 将List获得交给工厂声明类型和实现类 解耦合
ListFactory {
public static List getList(){
return new ArrayList(); // ----> 方法跟类解耦合
}
}
接着在利用读取配置文件,利用反射技术构造实例
Class.forName(类名).newInstance();
------》 配置文件中配置
list = java.util.ArrayList();
这样要是想让List获得不同的实例,只要修改配置文件中的配置即可。
接口 o = 工厂.获得接口实例();
在工厂中将A和B配置到 配置文件,读取配置文件,通过反射构造实例
这就是 利用 工厂+反射 + 配置文件 来解耦合
spring的思想就是 利用上述 模式思想,将对象的创建权, 反转给了Spring容器。
1.首先在src下建立applicationContext.xml的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- 将HelloService对象创建权 交给Spring -->
<bean id="helloService" class="cn.itcast.spring.quickstart.HelloService">
</beans>
这样创建HelloService 对象的权利就交给了Spring的容器。
public class HelloTest{
public static void main(String[ args){
// 使用Spring Ioc 方式 获得HelloService 实例
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); // 获得工厂实例
HelloService helloService2 = (HelloService) applicationContext.getBean("helloService"); // 通过id获得实例
//helloService2.setInfo("itcast"); // 已经配置依赖注入
helloService2.sayHello();
<span style="white-space:pre"> </span>}
}