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);在doGet()或doPost()方法使用如下:
DataBean OraDatabase =(DataBean) appctx.getBean("dataBean");
注:Myservlet 是servlet的名字;DataBean 是实际spring中注册的bean;dataBean为spring中注册bean的id
当心:WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
不要写成:WebApplicationContextUtils.getWebApplicationContext(getServletContext());
要不然会经常得到【空指针异常】
评论