ClassPathXMLApplication
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
System.out.println(applicationContext.getBean("user1"));
}
}
ClassPathXMLApplication的路径是相对路径,文件路径在这:
加载的是编译文件路径下的spring.xml,找到了文件所以能注册取出bean。
FilePathXmlApplication
public class Main {
public static void main(String[] args) {
/*ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");*/
FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext("spring.xml");
System.out.println(applicationContext.getBean("user1"));
}
}
报错:
报找不到此文件的错误
修改:
public class Main {
public static void main(String[] args) {
/*ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");*/
FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext("src/main/resources/spring.xml");
System.out.println(applicationContext.getBean("user1"));
}
}
原因是:这里的参数是相对当前工程的路径
绝对路径的写法
public class Main {
public static void main(String[] args) {
/*ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");*/
FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext("D:\\项目\\spring-study\\FunnySpring\\src\\main\\resources\\spring.xml");
System.out.println(applicationContext.getBean("user1"));
}
}
照样可以正常定位到文件。
但是ClassPathXMLApplication不支持绝对路径的写法