一:简述:ApplicationContext是继承BeanFactory接口的接口,因此拥有BeanFactory的全部功能,ApplicationContext实际上可以理解为我们平时所说的Spring容器。ApplicationContext与BeanFactory最大的不同就是前者实例化后(即实例化容器后),里面的单实例Bean也会被实例化,而后者则是仅仅实例化了容器(BeanFactory也可以充当Spring容器),里面的单实例Bean是不会被实例化的,相当于懒加载,只有被调用的使用才会被实例化
二:ApplicationContext的具体实现(Spring容器的具体实现)
1.ClassPathXmlApplicationContext:从指定类路径下加载配置文件(xml文件),进而完成容器实例化的工作
2.FIleSystemXmlApplicationContext:从指定文件系统路径下加载xml配置文件,完成容器实例化工作
3.WebXmlApplicationContext::从Web应用程序中找到指定的xml配置文件,完成容器实例化工作。该容器多指web模块的容器(webMVC), web模块会独立于Spring容器,拥有自己的一个子容器。WebApplicationContextUtils类的getWebApplicationContext(ServletContext sc)方法可以获取到WebMVC的ioc容器,进而获取到容器里面的Bean实例(在SpringMVC中自定义Session监听器时非常有用)
三:实例化工作
1.手动实例化:
@Test
public void LoadContext() {
//示例通过从类路径下加载配置文件来实例化Spring容器
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("ApplicationContext.xml");
//获取容器中的Bean实例
Service bean = context.getBean("service",Service.class);
2.自动实例化:(在web应用程序启动的时候实例化容器·)
①通过Listener监听器实例化:
//通过ContextLoaderListener监听器实例化容器(实例化Spring容器常用)
//配置参数,指定实例化Spring容器需要的XML文件路径
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringApplicationContext.xml</param-value>
</context-param>
//通过ContextLoaderListener监听器实例化容器(Listener的初始化先于Srvlet初始化)
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
②通过Servlet实例化
//通过ContextLoaderServlet实例化容器,一般用作实例化WebMVC的容器
//配置参数,指定位置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringApplicationContext.xml</param-value>
</context-param>
//指定以Servlet方式启动Spring容器
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
----------------------------------------------------------------------------------------
//实例化WebMVC的容器
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springWebmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>