Spring中ClassPathXmlApplication與FileSystemXmlApplicationContext的區別
一、概述
在項目中遇到加載不到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 目錄。
示例:
@Test
public 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:” 前綴可以缺省。
示例:
@Test
public 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());
}