1
我打算在Spring MVC應用程序中做一些事情。在Spring MVC的@Service類中加載靜態的.xml文件
- 負載與配置的靜態.xml文件在我
ConfigFactory
類@Service
註解。 - 做一些解析並創建一個
Configuration
類的實例。 - 將此
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 ServletContext
我ConfigurationFactory
和加載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; (...)
你是可以將靜態文件重新定位到ConfigurationFactory所在的類路徑(「WEB-INF/classes」或者.jar中,如果捆綁在單獨的.jar中?這樣你就不會依賴真正的文件路徑,並且你可以在你的'ConfigurationFactory'內部執行'getClass()。getResourceAsStream(「/ config/sampleItem.xml」)'。 –
感謝您的評論。的確,將它移動到classpath並使用'ClassPathResource'解決了這個問題。 – Disper