2013-07-05 55 views
1

我打算在Spring MVC應用程序中做一些事情。在Spring MVC的@Service類中加載靜態的.xml文件

  1. 負載與配置的靜態.xml文件在我ConfigFactory@Service註解。
  2. 做一些解析並創建一個Configuration類的實例。
  3. 將此Configuration類傳遞給AnotherServiceClass,這將創建一個model,我想稍後傳遞給view

該靜態文件位於'WEB-INF/config/sampleItem.xml`位置。

當我嘗試做的第一步我@Controller ItemController我沒有與任何問題,因爲我有機會在那裏ServletContext

@Autowired ServletContext servletContext; 

public ModelAndView method(){ 
    File xmlFile = new File(servletContext.getRealPath("/WEB-INF/config/sampleItem.xml")); 
    Document config = new SAXBuilder(XMLReaders.NONVALIDATING).build(xmlFile); 
    ... 
} 

但我不知道如何在我的@Service classes中實現它。當我在它的構造函數中再次試圖@Autowiring ServletContextConfigurationFactory和加載XML具有相同:

File xmlFile = new File(servletContext.getRealPath("/WEB-INF/config/sampleItem.xml")); 

我結束了一個例外:

Error creating bean with name 'itemController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.package.service.configuration.ConfigFactory org.package.controller.ItemController.configFactory; (...) 
+1

你是可以將靜態文件重新定位到ConfigurationFactory所在的類路徑(「WEB-INF/classes」或者.jar中,如果捆綁在單獨的.jar中?這樣你就不會依賴真正的文件路徑,並且你可以在你的'ConfigurationFactory'內部執行'getClass()。getResourceAsStream(「/ config/sampleItem.xml」)'。 –

+0

感謝您的評論。的確,將它移動到classpath並使用'ClassPathResource'解決了這個問題。 – Disper

回答

3

我通過管理來解決這個問題移動我的靜態XML爲src/main/resources,並在我的Service類加載它,而無需使用ServletContext有:

Resource myData = new ClassPathResource("sampleItem.xml"); 
File xmlFile = myData.getFile();