2010-03-04 67 views
3

我想在我的Spring MVC項目中檢索xml文件(包含bean定義)。 如果我在WEB-INF目錄下有xml文件,那麼我應該在我的servlet中的FileSystemResource中放入什麼路徑來檢索xml?Spring框架中的FileSytemResources

i.e. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("xml")); 

感謝

回答

2

你不應該使用FileSystemResource,你應該使用ServletContextResource

new ServletContextResource(servletContext, "/myfile.xml"); 

假設,當然,前提是ServletContext的是提供給您。

如果你真的想要使用FileSystemResource,那麼你需要問容器的目錄是哪裏,並使用它作爲相對路徑,例如,

String filePath = servletContext.getRealPath("/myfile.xml"); 
new FileSystemResource(filePath); 

儘管如此,Spring更容易讓你爲你工作。假設你有一個需要這個Resource的bean。您可以將資源路徑注入爲String,並讓Spring將其轉換爲資源,例如

public class MyBean { 

    private Resource myResource; 

    public void setMyResource(Resource myResource) { 
     this.myResource = myResource; 
    } 
} 

,並在你的bean文件:

<bean id="myBean" class="MyBean"> 
    <property name="myResource" value="/path/under/webapp/root/of/my/file.xml"> 
</bean> 

Spring將資源路徑轉換爲ServletContextResource並傳遞給你的bean。

+0

謝謝!在我的servlet中,我有HttpServletRequest和HttpServletResponse,所以我使用「request.getRealPath()」而不是servletContext.getRealPath()。 – portoalet 2010-03-04 14:36:35

+0

救了我的命! – rpr 2011-07-23 21:45:03