1.通过Spring提供的工具类获取ApplicationContext对象
import
javax.servlet.ServletContextEvent;
import
javax.servlet.ServletContextListener;
import
org.springframework.context.ApplicationContext;
import
org.springframework.web.context.WebApplicationContext;
import
org.springframework.web.context.support.WebApplicationContextUtils;
public
class
InitServletContextListener
implements
ServletContextListener {
private
static
WebApplicationContext springContext;
public
InitServletContextListener() {
super
();
}
public
void
contextInitialized(ServletContextEvent event) {
springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
}
public
void
contextDestroyed(ServletContextEvent event) {
}
public
static
ApplicationContext getApplicationContext() {
return
springContext;
}
}
2.将继承该监听器接口的类配置到web.xml文件中:
<!-- 用于初始化数据的监听器 -->
<listener>
<listener-class>包名.InitServletContextListener</listener-class>
</listener>
获取时
InitServletContextListener.getApplicationContext().getBean(
"testService"
);
3.另外,在web容器启动时初始化数据:
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class InitServletContextListener implements ServletContextListener {
/**
* 当Servlet 容器启动Web 应用时调用该方法。在调用完该方法之后,容器再对Filter 初始化,
* 并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。
*/
public void contextInitialized(ServletContextEvent sce) {
/*获取ServletContext对象*/
ServletContext application = sce.getServletContext();
// 得到Service的实例对象
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(application);
PrivilegeService testService = (PrivilegeService) ac.getBean("testService");
List<?> testList = testService.findAll();
application.setAttribute("testList", testList);
}
/**
* 当Servlet 容器终止Web 应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet 和Filter 过滤器。
*/
public void contextDestroyed(ServletContextEvent sce) {
}
}