這兩者在功能上完全等同,只是一個是基於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> |
通過以上配置,Web容器會自動加載/WEB-INF/applicationContext.xml初始化
ApplicationContext實例,如果需要指定配置文件位置,可通過context-param加以指定:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>
配置完成之後,即可通過
WebApplicationContextUtils.getWebApplicationContext方法在Web應用中獲取ApplicationContext引用。
如:ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext();
LoginAction action=(LoginAction)ctx.getBean("action");
-------------------------------------------------------------------------------------------
spring爲ApplicationContext提供有三種實現(舉例)
1. FileSystemXmlApplicationContext
eg1. ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); //加載單個配置文件
eg2.
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new FileSystemXmlApplicationContext(locations ); //加載多
eg3.
2. ClassPathXmlApplicationContext
eg1. ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
eg2.
String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new ClassPathXmlApplication(locations);
注:其中FileSystemXmlApplicationContext和ClassPathXmlApplicationContext與BeanFactory的xml文件定位方式一樣是基於路徑的。
3. XmlWebApplicationContext
eg1. ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);