在servlet、filter、Taglib中获取Spring Bean
来源:互联网 发布:站长工具 端口测试 编辑:程序博客网 时间:2024/05/18 03:32
在servlet容器中使用spring框架时spring的上下文(WebApplicationContext)被在保存在 ServletContext中。在servlet、filter或jsp标签中获取spring bean的关键在于如何获取ServletContext。
servlet中:
public void init(ServletConfig config){
servletContext= config.getServletContext();
}
filter中:
public void init(FilterConfig config) throws ServletException {
ServletContext servletContext =config.getServletContext();
}
jsp taglib中:
ServletContext servletContext = this.pageContext.getServletContext();
spring的上下文(WebApplicationContext)存在ServletContext以 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE为key的属性中,可通过如下方式获取:
Object ob = servletContext .getAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
WebApplicationContext context = (WebApplicationContext) ob;
在WebApplicationContext中获取bean:
protected Object getBean(String name){
return this.getWebApplicationContext().getBean(name);
}
一个抽像的servlet基类:
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.Servlet;
import org.springframework.web.context.WebApplicationContext;
public abstract class BaseServlet implements Servlet {
protected ServletContext servletContext;
public void init(ServletConfig config){
servletContext= config.getServletContext();
}
public ServletContext getServletContext(){
return servletContext;
}
public void destroy(){
}
public String getServletInfo(){
return "";
}
protected WebApplicationContext getWebApplicationContext()
throws RuntimeException{
Object ob = servletContext.getAttribute(WebApplicationContext
.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
WebApplicationContext context = (WebApplicationContext) ob;
return context;
}
protected Object getBean(String name){
return this.getWebApplicationContext().getBean(name);
}
public ServletConfig getServletConfig(){
return null;
}
}
- 在servlet、filter、Taglib中获取Spring Bean
- 在servlet中或者在filter中获取spring容器中的bean
- 在servlet中获取spring Bean对象
- Filter或Servlet中获取Spring Bean的方法
- 在filter中获取spring容器中的bean对象
- 通过spring在filter注入bean(DelegatingFilterProxy与servlet filter)
- 通过spring在filter注入bean(DelegatingFilterProxy与servlet filter) .
- 在servlet中获取spring管理的bean
- 在Servlet中获取Spring的指定bean
- 在Servlet中获取spring管理的bean
- Filter中获取Spring的bean
- 如何在servlet 获取spring bean
- Servlet,Webservice中spring 获取Bean方式
- servlet 中获取 spring 管理的 bean
- servlet中手动获取spring的bean
- servlet中获取spring管理的bean
- servlet 中获取 spring 管理的 bean
- Servlet获取Spring bean
- SWT/JFace中Table相同列多种类型CellEditor以及参照类型编辑器的实现
- SWT实现简易Cron表达式编辑器
- Java多线程之并发协作生产者消费者设计模式
- Tomcat配置多个端口号或多个应用,使得域名后面加不同端口访问
- 操作系统——进程间通信和调度
- 在servlet、filter、Taglib中获取Spring Bean
- Ubuntu16.04开机登陆后直接进入命令行界面
- struts2 迭代标签获取list集合的两种情况
- redis-3.0 主从复制
- 操作系统——存储管理
- JSP —— scope取值page、request、session、application
- Django底层剖析之一次请求到响应的整个流程
- 上传本地代码到github
- String.format(String format, Object… args)总结