Web中使用普通类得到applicationContext

xiaoxiao2021-03-01  7

用一个类来存放applicationContext:   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);  
转载请注明原文地址: https://www.6miu.com/read-3650317.html

最新回复(0)