[英]Loading spring XML from location different from classpath to get a bean in Servlet
I have a Servlet
class that is supposed to get data from service and write the data back to servlet response. 我有一个Servlet
类,它应该从服务中获取数据并将数据写回servlet响应。 The service
class is already declared in spring xml ( dispatcher-servlet.xml
). service
类已在spring xml( dispatcher-servlet.xml
)中声明。 So I want to get the service class bean
from dispatcher-servlet.xml
. 所以我想从dispatcher-servlet.xml
获取service class bean
。
I tried below code 我试过下面的代码
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:../WebContent/WEB-INF/dispatcher-servlet.xml");
ServiceImpl serviceImpl = (ServiceImpl) context.getBean("service");
and below code 以下代码
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");
but those these are throwing FileNotFoundException
但是那些正在抛出FileNotFoundException
If I move the dispatcher-servlet.xml
to src
folder, it works fine. 如果我将dispatcher-servlet.xml
移动到src
文件夹,它可以正常工作。 But I can't move it because the dispatcher-servlet.xml has been there in WEB-INF for long time many other classes are using it. 但是我无法移动它,因为dispatcher-servlet.xml已经在WEB-INF中存在了很长时间很多其他类正在使用它。 dispatcher-servlet.xml
is declared in Web.xml properly and it loads and works properly. dispatcher-servlet.xml
在Web.xml中正确声明,并且加载并正常工作。
Only issue is I am unable to load it from the java code in servlet class. 唯一的问题是我无法从servlet类中的java代码加载它。
The location of the dispatcher-xml is /WebContent/WEB-INF/dispatcher-servlet.xml dispatcher-xml的位置是/WebContent/WEB-INF/dispatcher-servlet.xml
Any pointers or workarounds are highly appreciated. 任何指针或变通方法都非常受欢迎。 Thanks. 谢谢。
WEB-INF
is added to classpath WEB-INF
被添加到类路径中
You can try below code 你可以尝试下面的代码
ApplicationContext context = new FileSystemXmlApplicationContext
("classpath:/../dispatcher-servlet.xml");
Consider reading about what the classpath is and which parts of a web app are added to the classpath as advised by Sotirios Delimanolis 根据Sotirios Delimanolis的建议,考虑阅读类路径是什么以及将Web应用程序的哪些部分添加到类路径中
In your servlet code, have you tried: 在您的servlet代码中,您尝试过:
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext(),
"org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
You'll need to ensure that your servlet is initialised after the dispatcher servlet in the web.xml (use the load-on-startup
element). 您需要确保在web.xml中的调度程序servlet之后初始化servlet(使用load-on-startup
元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.