前面说过,由Spring IOC容器管理的对象称之为bean。简单的讲,它是由Spring容器初始化,装配及管理的对象,除此之外,bean就余应用程序里面的其它对象差不多了。
也就是说,IOC这种思想是靠Spring容器管理bean实现的,Spring容器管理bean对象我们就可以称之为IOC(控制反转),具有控制反转功能的容器我们就成为IOC容器。
我们要研究透彻IOC就必须还要探究bean的实现原理。
org.springframework.beans.factory.BeanFactory是Spring IOC容器的实际代表者,但在实际开发中,我们一般使用的是ApplicationContext,虽然BeanFactory接口实现了IOC的核心功能,但是ApplicationContext在核心功能上增加了,譬如
1.支持不同的信息源
2.访问资源
3.支持应用事件
4.在Apllication中提供的附加服务
,也就是说如果BeanFactory的实现是IOC的基本形式,ApplicationContext是IOC的高级形式,ApplicationContext提供了比BeanFactory更加丰富的功能,便于实际开发中使用。
IOC在Spring中的接口设计:
首先找到我们最关心的两个接口BeanFactory和ApplicationContext,我们可以看到ApplicationContect除了继承BeanFactory的子接口还继MessageSource,ResourceLoader以及ApplicationEventPublisher接口,所以ApplicationContext接口就是在BeanFactory的基础上增加了其它丰富的功能,而MessageSource,ResourceLoader以及ApplicationEventPublisher这三个接口也分别表示信息源,访问资源和应用事件
然后我们观察BeanFacotry接口以及它的三个子接口,我们通过其源代码可以发现:
1.BeanFactory接口定义了基本的IOC容器规范,它包括了getBean()这样的IOC容器基本方法(从容器中获得bean)
2.HierarchicalBeanFactory增加了getParentBeanFactory()方法,使BeanFactory增加了双亲IOC容器的管理功能,其子接口ConfigurableBeanFactory又增加了setParentBeanFactory()(设值双亲IOC容器管理功能)和addBeanPostProcessor()(配置Bean后置处理器)等方法
3.ListableBeanFactory和AutowiredCapableBeanFactory和MessageSource,ResourceLoader以及ApplicationEventPublisher这三个接口功能类似,都是丰富了基本接口的功能
Spring IOC包括1.找到bean 2.载入bean 3.在Spring容器中注册bean这三个步骤
如上图,Spring IOC容器将读取配置元数据,并对其实例化,配置以及组装,所以Spring IOC容器中最基本的bean是单个对象的形式,通过对单个对象的组装形成多个对象组成的bean,来满足我们的业务需求
然后我们来看一看bean在Spring中的具体配置实现:
第一种类型:最简单的配置(单个对象的bean形式)
<?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-2.5.xsd">
<bean id="bean1" class="com.test1">
</bean>
<bean id="bean2" class="com.test2">
</bean>
</beans>
第二种类型:通过依赖注入DI来实现bean的配置(包括设值注入,构造器注入,静态工厂注入和实例工厂注入)
第三种类型:注入集合值(用来注入List,Set,Map和Properties)
<bean id="moreComplexObject" class="example.ComplexObject">
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.org</prop>
<prop key="support">support@example.org</prop>
<prop key="development">development@example.org</prop>
</props>
</property>
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource" />
</list>
</property>
<property name="someMap">
<map>
<entry>
<key>
<value>an entry</value>
</key>
<value>just some string</value>
</entry>
<entry>
<key>
<value>a ref</value>
</key>
<ref bean="myDataSource" />
</entry>
</map>
</property>
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource" />
</set>
</property>
</bean>
这三种类型是我个人定义的,只是为了方便理解,关于Bean还有其它的很多特性,这里就不阐述了,可以阅读相关的文档,如果有地方定义的不够准确,欢迎指出
参考资料:Spring官方文档(这里基于Spring3.x进行讨论,高版本无非增加了部分新特性,研究透彻核心,无论哪个版本都很好理解)
《Spring技术内幕》这本书值得一看,作为对Spring的理解会更深入