弹簧豆配置
我使用Spring的依赖注入,但我遇到了难以加载我的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项目中做我的Spring配置,而不是Java项目,还是这很重要?
如果它需要位于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());
我真的不记得为什么这样的事情,而是尝试把一个星号()在冒号(:)类路径面前:/如果THI s不起作用,请尝试冒号后面的星号(classpath:*),尽管我认为它在冒号之前。
我只在J2SE中使用了<import>
指令,它的工作原理没有classpath:
前缀,就像<import resource="config/resources.xml" />
一样。但在J2EE中,如果所有文件都在WEB-INF内部,它应该是相似的,只需导入resource =“bla.xml”并找到它即可,但在J2EE中,您不需要这样做,因为在web.xml中可以在web.xml中的contextConfigLocation
上下文参数中定义多个文件,只需用空格或换行符分隔它们即可。
我遇到了一个与red5插件类似的问题。我这样解决它:
try {
subContext = new FileSystemXmlApplicationContext(new String[] { "classpath*:/myconfig.xml" }, true, context);
} catch (Exception fnfe) {
subContext = new FileSystemXmlApplicationContext(new String[] { "plugins/myconfig.xml" }, true, context);
}
这将看起来在classpath的任何地方,包括在包含我的代码的jar。如果发生异常,则检查插件目录。它可能不是最好的解决方案,但它的工作原理。
我想你是指这个:http://static.springframework.org/spring/docs/2.5.x/reference/resources.html#resources-classpath-wildcards – 2008-11-17 19:11:51