Web开发中获取Spring的ApplicationContext的三种方式
前两天在写这编文章的时候出了N次错,今天还是决定重新把它简单的记录一下。
?
在 WEB 开发中,可能会很少需要显示的获得 ApplicationContext 来得到由 Spring 进行管理的某些 Bean, 今天我就遇到了,在这里和大家分享一下, WEB 开发中,怎么获取 ApplicationContext
一?????? 要想怎么获取 ApplicationContext, 首先必须明白 Spring 内部 ApplicationContext 是怎样存储的。下面我们来跟踪一下源码
首先:从大家最熟悉的地方开始?
org.springframework.web.servlet.FrameworkServlet.CONTEXT.dis 其中dis为DispatcherServlet在web.xml中的配置名字。
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
public String getServletContextAttributeName() {
return SERVLET_CONTEXT_PREFIX + getServletName();
}
public static final String SERVLET_CONTEXT_PREFIX = FrameworkServlet.class.getName() + ".CONTEXT.";
public final String getServletName() {
return (getServletConfig() != null ? getServletConfig().getServletName() : null);
}