博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring框架的IoC容器详解
阅读量:4178 次
发布时间:2019-05-26

本文共 2155 字,大约阅读时间需要 7 分钟。

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文件即可

contextConfigLocation
/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml ...
org.springframework.web.context.ContextLoaderListener

  • 独立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。

转载地址:http://jclai.baihongyu.com/

你可能感兴趣的文章
轻松读懂字节码文件
查看>>
记一下对String#intern的理解
查看>>
Tomcat多种方式部署多个项目
查看>>
随机字符串
查看>>
ZipUtils工具类
查看>>
1071 - Specified key was too long; max key length is 767 bytes
查看>>
SQLSERVER的LOG文件过于庞大
查看>>
Mycat+SpringBoot完成分库分表
查看>>
基于JMH检验多种生成随机数方法的效率
查看>>
读写文件效率测试
查看>>
优雅停止 SpringBoot 服务
查看>>
轻松读懂WSDL文件
查看>>
FastJson中JSONPath的应用
查看>>
文件下载
查看>>
手动安装chrome插件
查看>>
mysql怎么把'1,2,3'转成1,2,3
查看>>
POI生成excel并设置过滤范围
查看>>
RSAUtils工具类
查看>>
常用的集合之间的转换
查看>>
list复制 浅拷贝和深拷贝
查看>>