2013-02-14 59 views
37

所有可見文件不是春

我創建了下面的MANIFEST.MF內部的JAR文件:

Manifest-Version: 1.0 
Ant-Version: Apache Ant 1.8.3 
Created-By: 1.6.0_25-b06 (Sun Microsystems Inc.) 
Main-Class: my.Main 
Class-Path: . lib/spring-core-3.2.0.M2.jar lib/spring-beans-3.2.0.M2.jar 

在其根部有被引用的文件名爲my.config像這樣我的春天的context.xml:

<bean id="..." class="..."> 
    <property name="resource" value="classpath:my.config" /> 
</bean> 

如果我運行jar,一切都看起來不錯escept特定文件的加載:

Caused by: java.io.FileNotFoundException: class path resource [my.config] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/work/my.jar!/my.config 
     at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:205) 
    at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52) 
    at eu.stepman.server.configuration.BeanConfigurationFactoryBean.getObject(BeanConfigurationFactoryBean.java:32) 
    at eu.stepman.server.configuration.BeanConfigurationFactoryBean.getObject(BeanConfigurationFactoryBean.java:1) 
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142) 
    ... 22 more 
  • 類是從
  • 彈簧和其它依賴被從分離罐
  • 彈簧上下文被裝入加載的罐子內部裝載的(新的ClassPathXmlApplicationContext(「彈簧上下文/ applicationContext.xml中」))
  • my.properties加載到PropertyPlaceholderConfigurer(「classpath:my.properties」)
  • 如果我把我的.config文件放在文件系統之外,並將資源url更改爲'file:',一切似乎都沒有問題。 ..

任何提示?

回答

77

如果你的spring-context.xml和my.config文件在不同的jar文件中,那麼你將需要使用classpath*:my.config

更多信息here

此外,還要確保從一個JAR文件中加載,當您使用resource.getInputStream()resource.getFile()

+1

他們在同一個罐子裏,但我試着用相同的結果你的解決方案:java.io.FileNotFoundException:類路徑資源[classpath *:my.config]無法解析爲URL,因爲它不存在 – BTakacs 2013-02-15 07:57:50

+0

我試圖將文件移動到'conf'目錄中,但它沒有幫助。 (文檔說:「這意味着像」classpath *:*。xml「這樣的模式不會從jar文件的根文件中檢索文件,而只能從擴展目錄的根文件檢索文件,這源於JDK的ClassLoader中的限制。 getResources()方法只返回傳入的空字符串的文件系統位置(指示可能的根搜索)。「) – BTakacs 2013-02-15 08:20:38

+0

奇怪的是:my.properties由PropertyPlaceholderConfigurer加載,log4j.properties已被sl4j找到.. 。他們在同一個位置...只是這個文件... – BTakacs 2013-02-15 16:35:17

1

我在使用Tomcat6.x時遇到了類似的問題,而且我找到的建議都沒有幫助。 最後我刪除了work文件夾(Tomcat)並且問題消失了。

我知道這是不合邏輯但對文檔目的...

6

我知道這個問題已經有了答案。然而,對於使用彈簧啓動的,這個環節幫我 - https://smarterco.de/java-load-file-classpath-spring-boot/

然而,resourceLoader.getResource("classpath:file.txt").getFile();造成這個問題,SBK的評論:

就是這樣。 java.io.File表示文件系統上的文件,目錄結構爲 。 Jar是一個java.io.File。但是該文件中的任何內容都不在java.io.File的範圍之內。至於java是 有關,直到它解壓縮,一個jar文件中的類是不是 不同於word文檔中的一個詞。

幫助我理解了爲什麼要使用getInputStream()代替。它現在適合我!

謝謝!