2010-01-16 79 views
1

我想使用BeanFactory創建bean,但我得到一個模糊:java.io.FileNotFoundException: \\WEB-INF\businesscaliber-servlet.xml在Spring中獲取FileNotFoundException

Resource res = new FileSystemResource("//WEB-INF//businesscaliber-servlet.xml"); 
BeanFactory factory = new XmlBeanFactory(res); 
if (factory != null && beanId != null) { 
    obj = factory.getBean(beanId); 
} 

他其使用該

的ApplicationContext環磷酰胺=新FileSystemXmlApplicationContext來工作( 「類路徑*:/ WEB-INF/businesscaliber-servlet.xml文件」);

回答

2

我相信你需要指定絕對路徑而不是指向FileSystemResource的Web應用程序相對路徑。

請嘗試使用ServletContextResource代替。

Resource實施 ServletContext資源, 解釋 web應用程序的根目錄中的相對路徑。

唯一的問題是你需要的ServletContext這樣:

ServletContext servletContext = ... 
Resource res = new ServletContextResource(servletContext, 
    "/WEB-INF/businesscaliber-servlet.xml"); 
BeanFactory factory = new XmlBeanFactory(res); 
if (factory != null && beanId != null) { 
    obj = factory.getBean(beanId); 
} 

值得一提的是理想,你會從ApplicationContext檢索此。從Spring Reference4.4 Resource Loader

Resource template = ctx.getResource("some/resource/path/myTemplate.txt); 

什麼會返回將是一個 ClassPathResource;如果針對 FileSystemXmlApplicationContext 實例執行相同的 方法,則會返回 FileSystemResource。對於 WebApplicationContext,你會得到 回到ServletContextResource和 等等。

因此,您可以以適合特定 應用程序上下文的 方式加載資源。

所以這是檢索資源的首選方法。

或者因爲/WEB-INF/在技術上是在classpath中,你可以使用classpath:前綴(根據您的評論),或使用ClassPathXmlApplicationContext(這將自動返回classpath下的資源)。

此外,沒有必要把雙斜槓。不知道你爲什麼這樣做。也許是從雙反斜槓,這是必要的擱置?

+0

它是新的ServletContextResource()正確的語法? – Vicky 2010-01-16 04:56:53

+0

我能找到解決方案使用此 ApplicationContext ctx = new FileSystemXmlApplicationContext(「classpath *:/ WEB-INF/businesscaliber-servlet.xml」); – Vicky 2010-01-16 05:32:49

相關問題