Spring动态获取IoC容器中管理的Bean
来源:互联网 发布:青岛php培训学校 编辑:程序博客网 时间:2024/05/29 18:34
原文链接:http://pbcljf.blog.163.com/blog/static/340340192010513537424/
Spring框架将DI模式发挥到了极至,因此,系统里面用Spring管理的Bean相互之间的获取是非常方便的,只要使用者提供一个setter方法并在配置文件中配置该属性就可以。
但是,对于系统中非Spring框架管理的类,如果需要获取Spring管理的类,或者,程序中需要动态的根据Be
an的id来获取Bean实例,不可能事先为该类提供所有需要的Bean属性的setter方法,在类似这样的情况下,
获取Spring框架管理的类实例的方法有多种,现在简单总结如下:
方法一:在初始化时保存ApplicationContext对象
代码:
ApplicationContext ac = new FileSystemXmlApplicationContext(”applicationContext.xml”);
ac.getBean(”beanId”);
说明:
这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。
方法二:通过Spring提供的工具类获取ApplicationContext对象
代码:
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContextsc)
ac1.getBean(”beanId”);
ac2.getBean(”beanId”);
说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后
在通过它获取需要的类实例。
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。
方法三:继承自抽象类ApplicationObjectSupport
说明:
抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationCont
ext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext
context)方法将ApplicationContext 对象注入。
方法四:继承自抽象类WebApplicationObjectSupport
说明:
类似上面方法,调用getWebApplicationContext()获取WebApplicationContext
方法五:实现接口ApplicationContextAware
说明:
实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对
象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。
以上方法适合不同的情况,请根据具体情况选用相应的方法。
这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知
道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运
行环境,尽量通过DI的方式获取需要的服务提供者。
本人认为,方法五比较可行,可以设计一个工具类,专门来获取Spring中的类。减少对业务代码的侵入性。
小龙推荐:动态获取IoC容器管理的Bean依赖于项目的运行环境,因此可以通过配置参数的方式选择实现方式
如果是C/S架构的项目,可以通过FileSystemXmlApplicationContext程序接口构造ApplicationContext对象;
如果是B/S架构的项目,可以通过Spring提供的工具类获取ApplicationContext对象,即第二种方法。
无论怎么实现,都需要注意加载的Spring配置文件的路径,推荐使用classpath取相对路径,方便项目的移植。
- Spring动态获取IoC容器中管理的Bean
- SSH中.动态获取spring IoC容器中管理的bean,dao
- SSH中.动态获取spring IoC容器中管理的bean,dao
- SSH中.动态获取spring IoC容器中管理的bean,dao
- Spring动态管理IoC容器中的Bean
- spring的IOC 容器管理 Bean
- Spring IOC容器中Bean的生命周期
- Spring IOC容器中Bean的生命周期
- spring 8 bean配置--IOC容器中bean的生命周期
- Spring 的 IOC 容器中 Bean 的生命周期
- 获取Spring 容器中bean的方法
- 获取spring容器中bean的方法
- Spring 学习第十天: IOC容器中Bean的生命周期
- Spring在 IOC 容器中 Bean 之间的关系
- Spring IOC容器中Bean的实例化过程
- 在Spring IOC容器中配置Bean
- 浅谈spring IOC容器中装配bean
- Spring IoC容器--Bean的装配
- Vector数据类型
- 快速排序算法
- 全面整理:在美国开车一定要知道的11个交通规则
- java面向对象1
- CSDN博客下载器v2.4发布
- Spring动态获取IoC容器中管理的Bean
- 解决FileZilla不能下载的问题
- Hibernate中多对多关系映射 、查询
- effective c++ 的50个最佳实践(二)
- 关于Linux的视频编程(v4l2编程)
- Oracle安全实战——开发完全的数据库与中间件环境
- 如何用word 2007在指定页插入页码和页眉页脚?
- 准备开发Metro Style 应用
- 远程线程注入详解