• 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中被广泛使用

  • 相关阅读:
    搭建WAP应用开发环境
    How To Recover Openfire admin Password
    Domino分区服务器的安装与设置
    apache安全加固
    apache的web文件根目录
    iis绑定域名
    dedecms出现Error: Errno:0 SQL::错误解决方法
    加入收藏兼容ie和火狐
    phpcms毛遂
    .htaccess文件
  • 原文地址:https://www.cnblogs.com/ilinuxer/p/6503303.html
Copyright © 2020-2023  润新知