org.springframework.web.context.support.WebApplicationContextUtils 提供靜態方法從 ServletContext 獲取 Spring 根上下文:
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
ContextLoaderListener 啟動時初始化根 ApplicationContext 並綁定到 ServletContext。
<%@ page import="org.springframework.context.ApplicationContext" %>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
TestService service = (TestService) ctx.getBean("testService");
out.print(service.test());
%>
ServletContext sc = getServletContext(); // 或 filterConfig.getServletContext()
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
public class MyAction extends ActionSupport implements ServletContextAware {
private ServletContext servletContext;
public void setServletContext(ServletContext sc) { this.servletContext = sc; }
public String execute() {
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// ...
}
}
web.xml 僅保留 ContextLoaderListener 與 DispatcherServlet,獲取方式完全相同。
WebApplicationContextUtilsWebApplicationContextUtils.getRequiredWebApplicationContext() 失快速失敗