[英]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.