zoukankan      html  css  js  c++  java
  • FileSystemXmlApplicationContext、ClassPathXmlApplicationContext和XmlWebApplicationContext简介

    今天在用Spring时遇到一个问题,提示找不到applicationContext.xml文件。原来是在加载这个文件时调用的方法不太合适,所以造成了程序找不到项目下的xml配置文件。

    我们常用的加载context文件的方法有如下三个:

    1、FileSystemXmlApplicationContext

    这个方法是从文件绝对路径加载配置文件,例如:

    ApplicationContext ctx = new FileSystemXmlApplicationContext( "G:/Test/applicationcontext.xml ");

    如果在参数中写的不是绝对路径,那么方法调用的时候也会默认用绝对路径来找,我测试的时候发现默认的绝对路径是eclipse所在的路径。

    采用绝对路径的话,程序的灵活性就很差了,所以这个方法一般不推荐。

    (如果要使用classpath路径,需要加入前缀classpath:   )

    2、ClassPathXmlApplicationContext

    这个方法是从classpath下加载配置文件(适合于相对路径方式加载),例如:

    ApplicationContext ctx = new ClassPathXmlApplicationContext( "/applicationcontext.xml ");

    该方法参数中classpath: 前缀是不需要的,默认就是指项目的classpath路径下面;这也就是说用ClassPathXmlApplicationContext时默认的根目录是在WEB-INF/classes下面,而不是项目根目录。这个需要注意!

    3、XmlWebApplicationContext

    专为web工程定制的方法,推荐Web项目中使用。例如:

    ServletContext servletContext = request.getSession().getServletContext();

    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

  • 相关阅读:
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
    Data Structure and Algorithm
  • 原文地址:https://www.cnblogs.com/henuyuxiang/p/3919457.html
Copyright © 2011-2022 走看看