对于Spring容器ApplicationContext的总结

一:简述: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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值