登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

love3400wind的blog

like

 
 
 

日志

 
 
 
 

Spring如何在servlet中获取Bean  

2011-01-05 13:42:23|  分类: IT |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

有两种方法:

1)、先添加servlet的静态方法:

private static Object servletfindBean(ServletContext servletContext,
   String beanName) {
  ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
  return appctx.getBean(beanName);
 }

在doGet()或doPost()方法使用如下:

ServletContext servletContext = request.getSession()    .getServletContext();

DataBean OraDatabase = (DataBean) Myservlet.servletfindBean( servletContext, "dataBean");

注:Myservlet 是servlet的名字;DataBean 是实际spring中注册的bean;dataBean为spring中注册bean的id

 

2)、在init方法中添加:

private ApplicationContext appctx = null;//定义全局变量context

public void init(ServletConfig config) throws ServletException {  super.init(config);
  appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
 }

在doGet()或doPost()方法使用如下:

DataBean OraDatabase =(DataBean) appctx.getBean("dataBean");

注:Myservlet 是servlet的名字;DataBean 是实际spring中注册的bean;dataBean为spring中注册bean的id

 

当心:WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

不要写成:WebApplicationContextUtils.getWebApplicationContext(getServletContext());

要不然会经常得到【空指针异常】

  评论这张
 
阅读(3120)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018