【问题标题】:Loading spring XML from location different from classpath to get a bean in Servlet从与类路径不同的位置加载 spring XML 以在 Servlet 中获取 bean
【发布时间】:2013-11-13 17:33:44
【问题描述】:

我有一个 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 应用程序的哪些部分添加到类路径中,哪些没有。

标签: java spring jakarta-ee spring-mvc


【解决方案1】:

WEB-INF 被添加到类路径

你可以试试下面的代码

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

考虑阅读类路径是什么,以及按照Sotirios Delimanolis 的建议将 Web 应用程序的哪些部分添加到类路径中

【讨论】:

  • 它适用于 ClassPathXmlApplicationContext,谢谢
【解决方案2】:

在您的 servlet 代码中,您是否尝试过:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多