Web开发中获取Spring的ApplicationContext的几种方式
在 WEB 开发中,获取到由 Spring 进行管理的某些 Bean,通常采用下面方式来获取
1、通过set注入方式
当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用 beanFactory
当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
public class SpringContext { private static ApplicationContext applicationContext; //Spring应用上下文环境 */ public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } } public class SpringContextLoaderListener extends ContextLoaderListener{ // public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); SpringContext.setApplicationContext( WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()) ); } } public class SpringContextLoaderServlet extends ContextLoaderServlet { private ContextLoader contextLoader; public void init() throws ServletException { this.contextLoader = createContextLoader(); SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext())); } }