spring 找不到applicationContext.xml解決方案

來源:互聯網
上載者:User

標籤:

初學Spring在用Resource rs=new ClassPathResource("applicationContext.xml");時老是遇到這個錯誤。後來發現用
ApplicationContext ctx=new FileSystemXmlApplicationContext("WebContent/WEB-INF/applicationContext.xml");可以解決這個問題。
仔細研究了下:
之所以我用ClassPathResource中找不到applicationContext.xml是因為我的這個xml檔案在建工程的時候預設放在了WebContent/WEB-INF/下面,但是用ClassPathResource是在目前的目錄也就是我這個java檔案所在的目下進行尋找。因此把這個xml檔案移動到我的src目錄下面就ok了。
同理如果是用ApplicationContext ctx=new ClassPathXmlApplicationContext()也是這樣是從當前路徑尋找,xml檔案應在目前的目錄下。
但是如果用FileSystemXmlApplicationContext呢,它是根據指定的路徑來進行尋找,所以要把路徑寫完整。現在xml路徑在src檔案夾下。那就要寫:ApplicationContext ctx=new FileSystemXmlApplicationContext("src/applicationContext.xml");
這是比較直接簡單的寫法,後來又查了查發現對於FileSystemXmlApplicationContext也可以採用:
1.加上classpath:首碼(這個時候xml要放在目前的目錄也就是src下)
ApplicationContext ctx=new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
2.加上file:把路徑寫全(用這個方法xml可以放任意地方)
ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext ctx=new ClassPathXmlApplicationContext("file:F:/workspace/SpringExercis/src/applicationContext.xml");
綜上,最簡單的方法還是老老實實把xml放在src下方便。

spring 找不到applicationContext.xml解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.