天天看點

ClassPathXmlApplicationContext和FileSystemXmlApplicationContext的差別

IOC思想基于IOC容器完成,IOC容器底層就是對象工廠

Spring提供IOC容器的兩種實作方式(兩個接口):

  • BeanFactory:IOC容器的基本實作,是Spring内部的使用接口

    注:加載配置檔案的時候不會建立對象,在擷取對象(使用)才去建立對象

  • ApplicationContext:BeanFactory接口的子接口,提供更多更強大的功能,一般由開發人員進行使用

    注:加載配置檔案的時候就會建立對象

下面介紹ApplicationContext常用的接口:

ClassPathXmlApplicationContext和FileSystemXmlApplicationContext的差別

一、ClassPathXmlApplicationContext

(1)空字首:預設掃描項目的classpath下相對路徑(即src包下的相對路徑)

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

(2)classpath字首:表示掃描的是項目的classpath下相對路徑

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean1.xml"); 
           

(3)file字首: 表示掃描的是檔案的絕對路徑

ApplicationContext context = new ClassPathXmlApplicationContext("file:D:/.../bean1.xml"); 
           

(4)可以同時加載多個檔案

String[] locations = {"classpath:bean1.xml","bean2.xml"}; 
ApplicationContext context = new ClassPathXmlApplicationContext(locations); 
           

(5)使用通配符加載所有符合要求的檔案

ApplicationContext context = new ClassPathXmlApplicationContext("bean*.xml"); 
           

二、FileSystemXmlApplicationContext

(1)空字首:預設為項目的根目錄(即項目包名下的相對路徑)

ApplicationContext context = new FileSystemXmlApplicationContext("src/bean1.xml"); 
           

(2)classpath字首:表示掃描的是項目的classpath下相對路徑

ApplicationContext context = new FileSystemXmlApplicationContext("classpath:bean1.xml"); 
           

(3)file字首: 表示掃描的是檔案的絕對路徑,不加file字首也是一樣的

ApplicationContext context = new FileSystemXmlApplicationContext("file:D:/.../bean1.xml"); 
ApplicationContext context = new FileSystemXmlApplicationContext("D:/.../bean1.xml"); 
           

(4)可以同時加載多個檔案

String[] locations = {"classpath:bean1.xml","bean2.xml"}; 
ApplicationContext context= new FileSystemXmlApplicationContext(locations);
           

(5)使用通配符加載所有符合要求的檔案

ApplicationContext context = new FileSystemXmlApplicationContext("classpath:bean*.xml"); 

           

綜上,ClassPathXmlApplicationContext和FileSystemXmlApplicationContext用法類似,僅僅是在參數預設情況下有所不同:前一個預設掃描src包下,後一個預設掃描project包(項目包)下