ClassPath与 FileSystem(ApplicatonContext)的区别
ClassPathXmlApplicationContext
-
classpath:
默认就是指项目的classpath路径下面,classpath:
可以缺省 -
如果要使用绝对路径,需要加上 file: 前缀表示这是绝对路径, 不可缺省
示例
public void testBean(){
//单配置文件方式一BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml");//单配置文件方式二BeanFactory beanFactory=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");//多个配置文件BeanFactory beanFactory=new ClassPathXmlApplicationContext(new String[]{
"applicationContext.xml"});//或者用通配符BeanFactory beanFactory=new ClassPathXmlApplicationContext("classpath:/*.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());
}
FileSystemXmlApplicationContext
-
没有盘符的是 项目工作路径, 即项目的根目录,
file:
前缀可以缺省。 -
有盘符表示的是 文件绝对路径
-
如果要使用classpath路径, 需要前缀
classpath:
示例
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());
}
参考
https://blog.csdn.net/danielzhou888/article/details/72852706
https://www.cnblogs.com/ninth/p/6841608.html