2008-11-17 223 views
5

我使用Spring的依賴注入,但我遇到了難以加載我的Spring配置文件中的資源。彈簧豆配置

該資源是一個XML文件,位於我的類路徑中的JAR文件中。我嘗試訪問它,如下所示:

<import resource="classpath:com/config/resources.xml" /> 

但我不斷收到遇到以下錯誤:

Failed to import bean definitions from URL location [classpath:com/config/resources.xml]

的JAR文件是Java項目的類路徑,這又被用我web應用程序。我真的應該在Web項目中做我的Spring配置,而不是Java項目,還是這很重要?

回答

10

如果它需要位於webapp的類路徑中,那麼您應該將包含配置文件的JAR放入您的WEB-INF/lib目錄中。

如果您使用的是Web應用程序,那麼通常的約定是使用的ContextLoaderListener來確保WebApplicationContext被插入在ServletContext的標準位置:

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:/com/config/resources.xml</param-value> 
</context-param> 

然後使用WebApplicationContextUtils魚應用程序上下文出來使用servlet上下文:

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); 
0

我真的不記得爲什麼這樣的事情,而是嘗試把一個星號()在冒號(:)類路徑面前:/如果THI s不起作用,請嘗試冒號後面的星號(classpath:*),儘管我認爲它在冒號之前。

+0

我想你是指這個:http://static.springframework.org/spring/docs/2.5.x/reference/resources.html#resources-classpath-wildcards – 2008-11-17 19:11:51

0

我只在J2SE中使用了<import>指令,它的工作原理沒有classpath:前綴,就像<import resource="config/resources.xml" />一樣。但在J2EE中,如果所有文件都在WEB-INF內部,它應該是相似的,只需導入resource =「bla.xml」並找到它即可,但在J2EE中,您不需要這樣做,因爲在web.xml中可以在web.xml中的contextConfigLocation上下文參數中定義多個文件,只需用空格或換行符分隔它們即可。

1

我遇到了一個與red5插件類似的問題。我這樣解決它:

try { 
    subContext = new FileSystemXmlApplicationContext(new String[] { "classpath*:/myconfig.xml" }, true, context); 
} catch (Exception fnfe) { 
    subContext = new FileSystemXmlApplicationContext(new String[] { "plugins/myconfig.xml" }, true, context); 
} 

這將看起來在classpath的任何地方,包括在包含我的代碼的jar。如果發生異常,則檢查插件目錄。它可能不是最好的解決方案,但它的工作原理。