我正在使用 Spring 的依赖注入(inject),但在我的 Spring 配置文件中加载资源时遇到了困难。
该资源是一个 XML 文件,位于我的类路径中的一个 JAR 文件中。我尝试按如下方式访问它:
<import resource="classpath:com/config/resources.xml" />
但是我不断遇到以下错误:
Failed to import bean definitions from URL location [classpath:com/config/resources.xml]
JAR 文件位于 Java 项目的类路径中,而我的 Web 应用程序又使用它。我真的应该在 Web 项目而不是 Java 项目中进行 Spring 配置吗?这有关系吗?
最佳答案
如果它需要在您的 webapp 的类路径中,那么您应该将包含配置文件的 JAR 粘贴到您的 WEB-INF/lib 目录中。
如果您使用的是 Web 应用程序,那么常见的约定是使用 ContextLoaderListener 来确保将 WebApplicationContext 插入到 ServletContext 中的标准位置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/com/config/resources.xml</param-value>
</context-param>
然后使用WebApplicationContextUtils使用以下方法从 servlet 上下文中获取应用程序上下文:
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
关于java - Spring bean 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/296312/