Spring中ClassPathXmlApplication與FileSystemXmlApplicationContext的區別

來源:互聯網
上載者:User

標籤: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的區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.