spring ApplicationContextAware的那些事儿
来源:互联网 发布:sql check约束表达式 编辑:程序博客网 时间:2024/05/20 17:23
在基于spring框架的B/S应用中,有时候需要在其他比如其他servlet等不属于spring容器范围中获取bean时,可用ApplicationContextAware来帮助我们。
废话不多说,直接上例子:
第一步,需要编写类实现ApplicationContextAware接口,如下面的AppUtil 类:
@Componentpublic class AppUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } public AppUtil(){ } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public static void setContext(ApplicationContext applicationContext){ AppUtil.applicationContext = applicationContext; } public static Object getBean(String paramString) { return applicationContext.getBean(paramString); }}
第二步,实现一个特定的servlet,如
public class ApplicationContextLoaderServlet extends HttpServlet { private static final long serialVersionUID = 1L;public void init(ServletConfig config) throws ServletException { AppUtil.setContext( WebApplicationContextUtils.getWebApplicationContext( config.getServletContext())); }}
第三步,将该servlet配置到web.xml
<servlet> <servlet-name>ApplicationContextLoaderServlet</servlet-name> <servlet-class> com.easyfee.core.web.servlet.ApplicationContextLoaderServlet </servlet-class> <load-on-startup>1</load-on-startup></servlet>
然后,童鞋们就可以再需要获得bean的地方进行使用了,如:
MyService myService = (MyService ) AppUtil
.getBean(“myService”);
希望这篇文章对大家有所帮助。
1 0
- spring ApplicationContextAware的那些事儿
- spring的那些事儿
- Spring的ApplicationContextAware解析
- Spring的ApplicationContextAware解析
- 聊聊Spring Cloud版本的那些事儿
- 聊聊Spring Cloud版本的那些事儿
- 说说Spring Cloud版本的那些事儿。
- 通过spring实现javamail的那些事儿
- Spring 的 ApplicationEvent ,ApplicationListener,ApplicationContextAware
- Spring中ApplicationContextAware的理解
- Spring中ApplicationContextAware的作用
- spring ApplicationContextAware
- Spring ApplicationContextAware
- Spring ApplicationContextAware
- Spring-ApplicationContextAware
- Spring ApplicationContextAware
- Spring-ApplicationContextAware
- Spring:ApplicationContextAware
- C#中HttpWebRequest的GetRequestStream执行的效率太低,甚至偶尔死掉
- 指針的檢測
- struts2 ResultType为chain的使用
- HDU 1253 胜利大逃亡 【BFS】
- hook模板x86/x64通用版(4)--CHook.cpp说明
- spring ApplicationContextAware的那些事儿
- 怎样学习才能拥有所谓“高并发”的经验?
- 116. Populating Next Right Pointers in Each Node && 117. II
- iOS命名规范
- leetcode104题 题解 翻译 C语言版 Python版
- 4269: 再见Xor 高斯消元求线性基
- c#之简单工厂设计模式
- 监听器
- 文件系统(嵌入式)对比分析