春豆配置

cdu*_*gan 5 java spring

我正在使用Spring的依赖注入,但是我在Spring配置文件中加载资源时遇到了困难.

资源是XML文件,位于类路径的JAR文件中.我尝试按如下方式访问它:

<import resource="classpath:com/config/resources.xml" />
Run Code Online (Sandbox Code Playgroud)

但是我一直遇到以下错误:

无法从URL位置导入bean定义[classpath:com/config/resources.xml]

JAR文件位于Java项目的类路径中,而我的Web应用程序又使用它.我应该真的在Web项目中进行Spring配置而不是Java项目,还是重要?

too*_*kit 10

如果它需要在您的webapp的类路径中,那么您应该将包含配置文件的JAR粘贴到您的WEB-INF/lib目录中.

如果您使用的是webapp,那么常见的约定是使用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>
Run Code Online (Sandbox Code Playgroud)

然后使用WebApplicationContextUtils使用以下命令从servlet上下文中捕获应用程序上下文:

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
Run Code Online (Sandbox Code Playgroud)