如何获取ApplicationContext
来源:互联网 发布:老司机 种子 知乎 编辑:程序博客网 时间:2024/06/05 04:13
最近事情比较多,好多东西不会,也没时间整理。这个是数据连接池的时候,不知道spring配置和tomcat下配置的区别,反正很多不知道。。。。
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(ServletContext sc)
ac1.getBean("beanId");
ac2.getBean("beanId");
说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。
方法三:继承自抽象类ApplicationObjectSupport
说明:
抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。
方法四:继承自抽象类WebApplicationObjectSupport
说明:
类似上面方法,调用getWebApplicationContext()获取WebApplicationContext
方法五:实现接口ApplicationContextAware
说明:
实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。
以上方法适合不同的情况,请根据具体情况选用相应的方法。
这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运行环境,尽量通过DI的方式获取需要的服务提供者。
- 如何获取ApplicationContext
- 如何获取ApplicationContext
- 获取ApplicationContext
- 如何在Java Web应用中获取Spring的ApplicationContext
- SpringMVC中在Filter中如何获取ApplicationContext对象
- spring框架下测试单元如何获取applicationContext
- 获取applicationContext、获取request
- 获取applicationcontext的方式
- applicationContext对象获取方法
- 获取ApplicationContext对象
- Spring获取ApplicationContext
- dubbo获取ApplicationContext
- spring获取ApplicationContext
- Spring MVC获取ApplicationContext
- javaweb获取ApplicationContext对象
- springmvc 获取ApplicationContext对象
- 获取spring ApplicationContext
- Java中获取 ApplicationContext
- 关于获取gridview里点击时获取对应的id号
- 读书笔记3:Head First设计模式——装饰者模式
- HDOJ 3729 - I'm Telling the Truth 水二分图最大匹配
- lsof
- 专家看好甲骨文-微软云计算合作计划
- 如何获取ApplicationContext
- PHP小镇微信平台开通,欢迎大家关注!
- 传微软将于7月1日宣布实施大规模重组
- 常量指针 和 指针常量
- sqlserver 读取类
- tput
- 对PPS文件的再编辑
- CIO还是CMO 大数据战略该由谁掌控?
- 启动VMware USB Arbitration Service服务时提示:错误31:连接到系统上的设备没有发挥作用