標籤:equals type 設定檔 多個 oid ini asc log 檔案
一、概述
在項目中遇到載入不到Spring設定檔,簡單分析後,寫此文備忘!
二、測試所需資源
TestBean.java
public class TestBean { public TestBean(){ System.out.println(this.getClass().getName().concat(" init !")); } public String getTestStr() { return "testStr"; }}
applicationContext.xml
<bean id="testBean" class="com.bean.TestBean" />
二、區別2.1 ClassPathXmlApplicationContext使用方法
ClassPathXmlApplicationContext 預設會去 classPath 路徑下找。classPath 路徑指的就是編譯後的 classes 目錄。
樣本:
@Testpublic void testBean(){ //單設定檔方式一 BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml"); //單設定檔方式二 BeanFactory beanFactory=new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //多個設定檔 BeanFactory beanFactory=new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); //絕對路徑需加“file:”首碼 BeanFactory beanFactory = new ClassPathXmlApplicationContext("file:E:\Workspace\idea_workspace\spring\springtest\src\main\resources\applicationContext.xml"); TestBean bean= (TestBean) beanFactory.getBean("testBean"); assertEquals("testStr",bean.getTestStr());}
運行樣本你會發現 “classpath:” 是可以預設的。
如果是絕對路徑,就需要加上 “file:” 首碼,不可預設。
2.2 FileSystemXmlApplicationContext使用方法
FileSystemXmlApplicationContext 預設是去項目的路徑下載入,可以是相對路徑,也可以是絕對路徑,若是絕對路徑,“file:” 首碼可以預設。
樣本:
@Testpublic void testBean(){ //classes目錄 BeanFactory beanFactory=new FileSystemXmlApplicationContext("classpath:applicationContext.xml"); //項目路徑相對路徑 BeanFactory beanFactory=new FileSystemXmlApplicationContext("src\\main\\resources\\applicationContext.xml"); //多設定檔 BeanFactory beanFactory=new FileSystemXmlApplicationContext(new String[]{"src\\main\\resources\\applicationContext.xml"}); //絕對目錄 BeanFactory beanFactory=new FileSystemXmlApplicationContext(new String[]{"E:\\Workspace\\idea_workspace\\spring\\springtest\\src\\main\\resources\\applicationContext.xml"}); TestBean bean= (TestBean) beanFactory.getBean("testBean"); assertEquals("testStr",bean.getTestStr());}
Spring中ClassPathXmlApplication與FileSystemXmlApplicationContext的區別