[转]Spring中ApplicationContext的获取方式
Spring中ApplicationContext加载机制。
加载器目前有两种选择:ContextLoaderListener和ContextLoaderServlet。
这两者在功能上完全等同,只是一个是基于Servlet2.3版本中新引入的Listener接口实现,而另一个基于Servlet接口实现。开发中可根据目标Web容器的实际情况进行选择。
配置非常简单,在web.xml中增加:
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class></listener>
<servlet> <servlet-name>context</servlet-name> <servlet-class> org.springframework.web.context.ContextLoaderServlet </servlet-class> <load-on-startup>1</load-on-startup></servlet>
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myApplicationContext.xml</param-value></context-param>
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(); LoginAction action=(LoginAction)ctx.getBean("action");