標籤:system 方式 cto context sys resources test ffffff contex
一、ClassPathXmlApplicationContext 的具體路徑
String s[] = System.getProperty("java.class.path").split(";");
for (String string : s) {
System.out.println(string);
}
排除掉lib以及C盤的,最後指向的是 ../target/classes/
所以把spring的xml放到main/resources下,Build-->make project(ctrl+F9)一下,即可在target產生,這時候使用以下語句就可以了
ApplicationContext bf = new ClassPathXmlApplicationContext("applicationContext.xml");
二、ClassPathXmlApplicationContext 使用方法
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());}
三、FileSystemXmlApplicationContext使用方法
public void testBean(){
//項目根目錄 BeanFactory beanFactory=new FileSystemXmlApplicationContext("applicationContext.xml");
//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的區別以及ClassPathXmlApplicationContext 的具體路徑