Spring框架的IoC容器详解

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。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值