2012-10-12 213 views
3

我在Spring中弄溼了我的手,並與Spring一起使用Eclipse。我已經用eclipse寫了一個非常簡單的Spring應用程序來在bean中注入一個屬性。但是,當我運行我的應用程序時,Spring正在拋出異常,並且Spring似乎無法找到Spring配置文件。下面是堆棧跟蹤 -Eclipse無法找到Spring配置文件

INFO: Loading XML bean definitions from class path resource [Beans.xml] 
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist 
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) 
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) 

我曾嘗試以下 - 給在ClassPathXmlApplicationContext的方法類似的完整路徑 -

ApplicationContext context = new ClassPathXmlApplicationContext("C:/Users/devshankhasharm/workspace/FinalPowerShell/src/src/main/Beans.xml"); 

我也更新了CLASSPATH變量在Windows中添加我的彈簧配置文件的路徑。但沒有任何工作。任何想法將不勝感激。

+2

由於錯誤提示您需要在classpath中有beans.xml,而您沒有,所以無法使用ClassPathXmlApplicationContext的完整路徑。請發佈你的項目結構和bean.xml的位置,如果你正在運行tomcat,那麼beans.xml會出現在web-inf/classes中 – Subin

+0

正如我上面提到的,我在windows中添加了classpath變量來包含Spring配置xml文件。有沒有什麼需要在Eclipse中完成更新類路徑來獲取我的配置文件。 – user496934

+0

yes右鍵單擊eclipse項目,選擇build path-> configure build path並檢查Source是否具有beans.xml所在的文件夾。我認爲windows中的類路徑環境變量不被認爲是通過eclipse計算類路徑 – Subin

回答

1

Beans.xml應該放在classpath中。您無法爲ClassPathXmlApplicationContext提供完整的xml文件物理路徑。請檢查Beans.xml是否存在於Eclipse的構建路徑中。

8

試試這個

ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:Beans.xml"); 

當然你Beans.xml必須在類路徑中。

更新也許

ApplicationContext context = new ClassPathXmlApplicationContext("file:src/main/Beans.xml"); 
+0

我也有問題,我不能加載Bean.xml。 \t雖然我將文件添加到類路徑中,但只能通過「classpath *:Beans.xml」加載。我怎樣才能通過「文件:Beans.xml」加載? – StellaMaris

+0

@StellaMaris如果'classpath *'正在工作,爲什麼需要通過'file:'加載? –

+0

因爲我對只爲'classpath *'工作的原因感興趣。並且我還有其他的[示例](我嘗試加載其中的一個[示例](http://stackoverflow.com/questions/36039062/load-hibernate-cfg-xml-in-existing-java-project/36039272?noredirect=1#comment59805602_36039272) hibernate.cfg.xml和因此我不能使用'classpath *'。 – StellaMaris

0

當你使用一個完整的文件路徑爲您的beans.xml例如,使用

ApplicationContext context = new GenericXmlApplicationContext("C:/Users/devshankhasharm/workspace/FinalPowerShell/src/src/main/Beans.xml"); 

,但不建議這樣做。改爲使用ClassPathXmlApplicationContext。

然後將Beans.xml移動到類路徑中。最簡單的方法是,如果使用Maven,如果不使用Maven或src/main/resources,則將其移動到Java源代碼的根目錄下。

0

如果沒什麼麻煩的話,可以嘗試使用Spring Tool Suite。它是基於Eclipse的Spring友好的IDE,因此您不必依賴於spring/maven插件配置。所有你需要做的就是去創建一個Spring項目而不是Java項目,並且休息所有的設置將會爲你處理。

0

如果您在使用Spring工具套件(STS),它可能是,當你創建一個Maven項目中的src/main/resources目錄與配置「除外:」的情況。換句話說,默認情況下,STS會將您的src/main/resources目錄設置爲從輸出中排除其所有內容。

如何解決此問題:

  1. 項目屬性(Alt + Enter鍵) - > Java構建路徑 - >源
  2. 上的src/main /資源,你可能會看到 「除外:。」
  3. 選擇該項目並點擊編輯...
  4. 刪除排除模式
  5. 單擊確定。瞧!
相關問題