Spring获取ApplicationContext的工具类
来源:互联网 发布:知乎怎样不让别人 编辑:程序博客网 时间:2024/06/05 06:34
在项目中,经常遇到这样的问题:有些类需要使用new来创建对象,但是类中需要使用spring容器中定义的bean,此时无法通过spring的自动注入来注入我们需要使用的bean。所以需要手动的从spring容器中获取bean。要获取bean必须先获取到ApplicationContext对象,有以下方式可以获取该对象。
方式一,手动创建ApplicationContext对象,并保存起来。
public class ApplicationContextUtil { private static ApplicationContext context; static { context = new ClassPathXmlApplicationContext("applicationContext.xml"); } public static ApplicationContext getApplicationContext() { return context; }}
方式二,在web环境中通过spring提供的工具类获取,需要ServletContext对象作为参数。然后才通过ApplicationContext对象获取bean。下面两个工具方式的区别是,前者在获取失败时返回null,后者抛出异常。另外,由于spring是容器的对象放在ServletContext中的,所以可以直接在ServletContext取出 WebApplicationContext 对象。
ApplicationContext context1 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); ApplicationContext context2 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);方式三,工具类继承抽象类ApplicationObjectSupport,并在工具类上使用@Component交由spring管理。这样spring容器在启动的时候,会通过父类ApplicationObjectSupport中的setApplicationContext()方法将ApplicationContext对象设置进去。可以通过getApplicationContext()得到ApplicationContext对象。
方式四,工具类继承抽象类WebApplicationObjectSupport,查看源码可知WebApplicationObjectSupport是继承了ApplicationObjectSupport,所以获取ApplicationContext对象的方式和上面一样,也是使用getApplicationContext()方法。
方式五,工具类实现ApplicationContextAware接口,并重写setApplicationContext(ApplicationContext applicationContext)方法,在工具类中使用@Component注解让spring进行管理。spring容器在启动的时候,会调用setApplicationContext()方法将ApplicationContext 对象设置进去。
@Componentpublic class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getApplicationContext() { return context; }}
- Spring获取ApplicationContext的工具类
- Spring获取ApplicationContext对象工具类
- 普通Java类获取Spring的ApplicationContext
- 普通Java类获取Spring的ApplicationContext
- Java类获取Spring的ApplicationContext
- 普通Java类获取Spring的ApplicationContext
- Java类获取Spring的ApplicationContext
- Java类获取Spring的ApplicationContext
- 怎么获取Spring的ApplicationContext
- 怎么获取Spring的ApplicationContext
- spring 获取 ApplicationContext的方法
- Spring获取ApplicationContext的方法
- 【转】普通Java类获取Spring的ApplicationContext
- Java类获取Spring的applicationContext.xml文件中的bean
- 获取Spring的ApplicationContext的方法
- JavaWeb中获取Spring的ApplicationContext
- spring获取ApplicationContext的方法-持续更新
- spring里头各种获取ApplicationContext的方法
- 小萌新的第一天
- Brtools扩oracle表空间
- C++Primer第五版 第九章习题答案(41~50)
- R中连接mysql数据库
- Java二叉树
- Spring获取ApplicationContext的工具类
- Android Studio中查看类的继承关系及文件结构
- Python_2
- JS简单实现多图片预览上传
- 管理后台的登录功能-重新思考
- cf 777c Alyona and Spreadsheet
- ONLINE方式在线重建索引异常中断后遇到ORA-08104错误的处理思路
- 解决PopupWindow在7.0以上位置不正确的bug
- OpenCV 装载、 显示和存储图像及在图像上绘图