IOC即inverse of control 控制反转
以前对象之间的引用是通过new来调用实现,有了Spring IOC,我们可以把对象之间的引用交给他来管理,这样就把控制权交给了Spring,所以就叫做控制反转。
Spring IOC的实现用到了设计模式:简单工厂,他也是从简单工厂进化而来的,下面我们看看Spring的IOC是如何进化来的。
简单工厂模式实现:
反射+简单工厂
但是工厂类如果这样写的话,就有一个问题,如果增加了水果,比如香蕉,那么在工厂类里面也要进行相关的修改了,这样不合理,而java的反射机制可以解决这个问题终极版本Spring IOC
加入配置文件问题就解决了,以后如果要增加新的水果类,都要在这个配置文件里面登记。这时我们可以说配置文件可以控制程序的执行,现在看起来有点像spring的ioc了。下面我们来看看Spring IOC是如何实现的。Bean.xml配置文件(该文件只要放在test2包里面就好了)
Test类
如此看来,你在对比一开始的那个水果的程序,你会发现,spring配置文件,还是一个工厂,只不过换种形式一样,他管理所有的类,新建的类要到工厂里面去登记,不然就不能被主程序用,这就是为什么说ioc就是工厂模式的升级版。至于配置文件的书写,就跟堆积木一样。
---------------------------------
顺便提下,关于Spring读取配置文件的方法:
applicationcontext---
FileSystemXmlApplicationContext---这个方法是从文件绝对路径加载配置文
ClassPathXmlApplicationContext---这个方法是从classpath下加载配置文件(适合于相对路径方式加载)
XmlWebApplicationContext----专为web工程定制的方法,推荐Web项目中使用。
beanfactory---
ClassPathResource --- 从系统的类路径中加载
FileSystemResource --- 从文件系统加载,比如说自己指定配置文件的全路径
InputStreamResource --- 从输入流中加载
ServletContextResource --- 从Servlet 上下文环境中加载
UrlResource --- 从指定的Url加载
FileSystemResource --- 从文件系统加载,比如说自己指定配置文件的全路径
InputStreamResource --- 从输入流中加载
ServletContextResource --- 从Servlet 上下文环境中加载
UrlResource --- 从指定的Url加载
---------------------------------------------
BeanFactory和ApplicationContext的区别
ApplicationContext接口,它由BeanFactory接口派生而来,因而提供BeanFactory所有的功能。ApplicationContext以一种更向面向框架的方式工作以及对上下文进行分层和实现继承,ApplicationContext包还提供了以下的功能:
• MessageSource, 提供国际化的消息访问
• 资源访问,如URL和文件
• 事件传播
• 载入多个(有继承关系)上下文 ,使得每一个上下文都专注于一个特定的层次,比如应用的web层
• MessageSource, 提供国际化的消息访问
• 资源访问,如URL和文件
• 事件传播
• 载入多个(有继承关系)上下文 ,使得每一个上下文都专注于一个特定的层次,比如应用的web层
最主要的就是BeanFactory延迟加载,当使用到getBean的时候才会抛异常,而ApplicationContext在刚开始启动加载的时候就会抛出异常,这样有利于检查所依赖属性是否注入;所以通常情况下我们选择使用ApplicationContext。