用一个类来存放applicationContext:
然后写一个servlet,继承自org.springframework.web.context.ContextLoaderServlet,并配置web.xml,让它在tomcat启动时自动运行。然后在它的init方法中,加入如下的代码:
- public class ContextHolder {
- private final static ContextHolder instance = new ContextHolder();
- private ApplicationContext ac;
- private ContextHolder() {
- }
- public static ContextHolder getInstance() {
- return instance;
- }
- public synchronized void setApplicationContext(ApplicationContext ac) {
- this.ac = ac;
- }
- public ApplicationContext getApplicationContext() {
- return ac;
- }
- }
然后写一个servlet,继承自org.springframework.web.context.ContextLoaderServlet,并配置web.xml,让它在tomcat启动时自动运行。然后在它的init方法中,加入如下的代码:
- WebApplicationContext context = WebApplicationContextUtils.
- getWebApplicationContext(this.getServletContext());
- ContextHolder.getInstance().setApplicationContext(context);