zoukankan      html  css  js  c++  java
  • spring容器ApplicationContext初始化(spring应用上下文初始化)

    可以通过以下三种方式加载spring容器,实现bean的扫描与管理:

    1、 ClassPathXmlApplicationContext:从类路径中加载

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
    context.start();

    2、 FileSystemXmlApplicationContext: 从文件系统加载

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("E:\spring-context.xml");
    context.start();

    3、 XmlWebApplicationContext:从web系统中加载

    即把spring容器加载到servlet容器(web容器)中,所以需要在web.xml文件中配置servlet或者listener的方式,实现spring容器的加载

    web.xml配置listener方式实现加载:

    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>/WEB-INF/spring-context.xml</param-value>  
    </context-param>

    web.xml配置servlet方式实现加载:

        <servlet>
            <servlet-name>springServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath*:/spring-mvc*.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>

    注意: 

    在spring MVC中,一般需要同时使用上面两种方式,servlet方式负责配置controller等view层,listener方式负责配置service、dao等model层。

    关于ContextLoaderListener和DispatcherServlet的关系与区别,可以详细看看下面的延伸文章(似懂非懂,暂时不做整理): 

    另外:关于web容器(servlet容器)加载spring容器及关系介绍:在servlet中注入spring的bean,servlet容器和spring容器

    4、补充:spring容器初始化使用到的基础包、类以及作用

    -org.springframework.beans 
    -BeanFactory提供配置结构和基本功能,加载并初始化Bean

    -org.springframework.context 
    -ApplicationContext保存了Bean对象并在Spring中被广泛使用

  • 相关阅读:
    memcached源码剖析5:并发模型
    memcached源码剖析4:并发模型
    深入剖析php执行原理(4):函数的调用
    深入剖析php执行原理(2):函数的编译
    剖析php脚本的超时机制
    strerror的坑
    深入理解php中的ini配置(2)
    深入理解php中的ini配置(1)
    一个“日期”字符串进行比较的case
    用valgrind检测php扩展内存泄露
  • 原文地址:https://www.cnblogs.com/ilinuxer/p/6503303.html
Copyright © 2011-2022 走看看