天天看點

Spring 中 ClassPathXmlApplicationContext 類的簡單使用

Spring 中 ClassPathXmlApplicationContext 類的簡單使用

部落客的學習記錄

  • ​​Docker彙總​​
  • ​​Redis彙總​​
  • ​​Vue彙總​​
  • ​​MyBatis Plus彙總​​
  • ​​微服務彙總​​
  • ​​Java網絡程式設計彙總​​
  • ​​Java設計模式彙總​​
  • ​​Java并發程式設計彙總​​
  • ​​消息中間件彙總​​

一、簡單的用 ApplicationContext 做測試的話 , 獲得 Spring 中定義的 Bean 執行個體(對象) 可以用:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");      

如果是兩個以上 , 可以使用字元串數組 :

ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","SpringTest.xml"});      

或者可以使用通配符:

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/*.xml");      
  1. ​classpath:​

    ​ 字首是可加可不加的 , 預設就是指項目的 classpath 路徑下面。
  2. 如果要使用絕對路徑 , 需要加上 ​

    ​file:​

    ​ , 字首表示這是絕對路徑。
  1. 沒有盤符的是項目工作路徑 , 即項目的根目錄。
  2. 有盤符表示的是檔案絕對路徑 ,​

    ​file:​

    ​ 可加可不加。
  3. 如果要使用 classpath 路徑 , 需要字首 ​

    ​classpath:​

    ​。
public class SpringTest {
  public static void main(String[] args) {
    // 用classpath路徑
    // ApplicationContext context = new ClassPathXmlApplicationContext("classpath:appcontext.xml");
    // ApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");

    // ClassPathXmlApplicationContext使用了file字首是可以使用絕對路徑的
    // ApplicationContext context = new ClassPathXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml");

    // 用檔案系統的路徑,預設指項目的根路徑
    // ApplicationContext context = new FileSystemXmlApplicationContext("src/appcontext.xml");
    // ApplicationContext context = new FileSystemXmlApplicationContext("webRoot/WEB-INF/appcontext.xml");


    // 使用了classpath:字首,這樣,FileSystemXmlApplicationContext也能夠讀取classpath下的相對路徑
    // ApplicationContext context = new FileSystemXmlApplicationContext("classpath:appcontext.xml");
    // ApplicationContext context = new FileSystemXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml");

    // 不加file字首
    ApplicationContext context = new FileSystemXmlApplicationContext("F:/workspace/example/src/appcontext.xml");
  }
}