怎么在servlet里面获取spring通过注解方式注入的service bean

2024-11-28 19:19:34
推荐回答(2个)
回答1:

自己写了一个方法获取。就可以正常像在action中获取了
获取的方式是IWxzfBIZ wxzfBIZ = (IWxzfBIZ)getBean("wxzfBIZ",request,response);
下面是方法

private WebApplicationContext ctx;

protected WebApplicationContext getWebApplicationContext(HttpServletRequest request,HttpServletResponse response) {
if (ctx == null)
ctx = initWebApplicationContext(request,response);
if (ctx == null)
throw new IllegalStateException(
"No WebApplicationContext found: no ContextLoaderListener registered?");
else
return ctx;
}

protected Object getBean(String name,HttpServletRequest request,HttpServletResponse response) {
return getWebApplicationContext(request,response).getBean(name);
}

protected WebApplicationContext initWebApplicationContext(HttpServletRequest request,HttpServletResponse response)
throws IllegalStateException {
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, request, response, null,true, 8192, true);
ServletContext sc = pageContext.getServletContext();
WebApplicationContext wac = (WebApplicationContext) sc
.getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX);
if (wac == null)
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
return wac;
}

private Map parseXmlToList2(String xml) {
Map retMap = new HashMap();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
org.jdom.Document doc = sb.build(source);
Element root = (Element) doc.getRootElement();// 指向根节点
List es = root.getChildren();
if (es != null && es.size() != 0) {
for (Element element : es) {
retMap.put(element.getName(), element.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retMap;
}

回答2:

  1.定义beanFactory类
  import org.springside.modules.utils.spring.SpringContextHolder;

  public class BeanFactory {

  public static Object getBean(String name) {
  return SpringContextHolder.getBean(name);
  }
  }
  2.使用
  ActivityManager activityManager = (ActivityManager)BeanFactory.getBean("activityManager");