您的位置:首页 > 编程语言 > Java开发

Spring框架的IoC容器详解

2016-03-20 23:27 801 查看
Spring框架的最大特性是提供了IoC容器。
谈到Spring框架的IoC容器,首先要明白Spring Bean的概念。Spring Bean特指由Spring IoC容器实例化、注入和管理的Java对象。

Spring IoC容器的核心是,在需要的时候通过名称直接引用Spring Bean,而无需编程创建Spring Bean的对象。如果一个Spring Bean还依赖其他Spring Bean, 则被引用的时候,先实例化被依赖的Spring Bean,然后再创建被引用的Spring Bean并将被依赖的Spring Bean注入。
1.Spring框架的IoC实现机制
1) BeanFactory接口
以工厂模式实现,提供对任何类型的对象的配置框架和基本功能
目前多用于集成第三方遗留系统(如Applet),通常应该避免使用
2) ApplicationContext接口
扩展了BeanFactory接口,更易于集成Spring的其他功能
ApplicationContext接口是事实上的IoC容器接口,负责Spring Bean的实例化、配置和注入
Web应用中,使用Spring IoC容器只需要配置web.xml文件即可
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml ...</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

独立Java应用中,常用的两个ApplicationContext接口的实现:

ClassPathXmlApplicationContext
FileSystemXmlApplicationContext

3) WebApplicationContext接口
扩展了ApplicationContext接口,专用于Web应用上下文环境中

2.IoC容器实例化Spring Bean的方式
无参数的构造函数
静态工厂方法(为了兼容遗留系统)
<bean id="clientService" class="examples.ClientService" factory-method="createInstanceMethod"/>
实例工厂方法
<!-- the factory bean, which contains a method called createClientServiceInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
   <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>

3.在Spring Bean中注入其依赖的其他Spring Bean的方式
构造函数的参数(Constructor-based DI),推荐
<bean id="bar" class="x.y.Bar"/>
<bean id="baz" class="x.y.Baz"/>
<bean id="foo" class="x.y.Foo">
   <constructor-arg ref="bar"/>
   <constructor-arg ref="baz"/>
   <constructor-arg type="int" value="1"/>
</bean>
属性的settor方法(Setter-based DI),适合于可选对象的注入

4.Spring IoC容器注入被依赖Spring Bean的过程
根据配置文件创建并初始化ApplicationContext(事实上的Bean工厂)
对于配置文件中的每个Spring Bean,实际被请求的时候才会实例化
(只有singleton域中的,且设置了pre-instantiate属性的Bean才会在初始化ApplicationContext的时候创建,详见后续文章)
创建Spring Bean的时候,首先创建并注入全部其所依赖的其他Spring Bean
利用动态代理的方式调用被依赖的Bean的方法

5.两个Spring Bean之间存在相互依赖的情况
如果彼此的依赖都是通过构造函数参数定义的,则IoC容器不能正确实例化Spring Bean,抛出异常BeanCurrentlyInCreationException
只要有一个依赖是通过settor方法定义的,则IoC容器能够正确实例化Spring Bean。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息