簡體   English   中英

從不同於classpath的位置加載spring XML以在Servlet中獲取bean

[英]Loading spring XML from location different from classpath to get a bean in Servlet

我有一個Servlet類,它應該從服務中獲取數據並將數據寫回servlet響應。 service類已在spring xml( dispatcher-servlet.xml )中聲明。 所以我想從dispatcher-servlet.xml獲取service class bean

我試過下面的代碼

            ApplicationContext context = new FileSystemXmlApplicationContext("classpath:../WebContent/WEB-INF/dispatcher-servlet.xml");
        ServiceImpl serviceImpl = (ServiceImpl) context.getBean("service");

以下代碼

            ServletContextResource res = new ServletContextResource(getServletContext(),"/WEB-INF/dispatcher-servlet.xml");
        ApplicationContext context = new FileSystemXmlApplicationContext("file:"+res.getURL()+"dispatcher-servlet.xml");
        ServiceImpl serviceImpl = (ServiceImpl) context.getBean("service");

但是那些正在拋出FileNotFoundException

如果我將dispatcher-servlet.xml移動到src文件夾,它可以正常工作。 但是我無法移動它,因為dispatcher-servlet.xml已經在WEB-INF中存在了很長時間很多其他類正在使用它。 dispatcher-servlet.xml在Web.xml中正確聲明,並且加載並正常工作。

唯一的問題是我無法從servlet類中的java代碼加載它。

dispatcher-xml的位置是/WebContent/WEB-INF/dispatcher-servlet.xml

任何指針或變通方法都非常受歡迎。 謝謝。

WEB-INF被添加到類路徑中

你可以嘗試下面的代碼

ApplicationContext context = new FileSystemXmlApplicationContext
              ("classpath:/../dispatcher-servlet.xml");

根據Sotirios Delimanolis的建議,考慮閱讀類路徑是什么以及將Web應用程序的哪些部分添加到類路徑中

在您的servlet代碼中,您嘗試過:

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext(),
"org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");

您需要確保在web.xml中的調度程序servlet之后初始化servlet(使用load-on-startup元素)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM