我有一个应用程序使用XML配置加载其Spring上下文。
上下文文件存储在jar的类路径中(在META-INF/context
目录中)。
在引入一个新bean时,我想从同一档案的类路径中加载beanio映射文件。
在Tomcat在Eclipse中运行的情况下,所有这些都具有吸引力,但是当我将WAR文件部署到我们的QA环境中时,应用程序无法启动。
让我来看看代码:
public class BeanIoParser implements Parser, Iterator<Message>, InitializingBean
{
private StreamFactory streamFactory;
private Resource resourceMapping; //Injected via Context
@Override
public void afterPropertiesSet() throws Exception
{
streamFactory = StreamFactory.newInstance();
streamFactory.load(resourceMapping.getFile()); //boom here
}
}
然后上下文
<bean id="messagesParser" class="it.acme.BeanIoParser" scope="prototype">
<property name="resourceMapping" value="classpath:META-INF/mappings/messages-beanio.xml" />
</bean>
然后什么?嗯...我已经通过首先解压缩war文件来仔细检查了内置的jar文件。全部匹配。
我可以正确看到
messages-beanio.xml
文件。但是,当我启动应用程序时,我得到了以下根本原因:
java.io.FileNotFoundException:类路径资源[META-INF / mappings / messages-beanio.xml]无法解析为绝对文件路径,因为它不驻留在文件系统中:jar:file:/ C:/ Program%20Files /Apache%20Software%20Foundation/Tomcat%208.0/temp/11-app/WEB-INF/lib/app-3.0.0.20151105.jar!/META-INF/mappings/messages-beanio.xml
我还尝试了另一种方式,通过使用
classpath*
(因为从多个jar文件加载Spring上下文时我们已经遇到了这个问题)所以如果我的bean声明变成
<property name="resourceMapping" value="classpath*:META-INF/mappings/messages-beanio.xml" />
我的错误变成
java.io.FileNotFoundException:ServletContext资源[/classpath*:META-INF/mappings/messages-beanio.xml]无法解析为绝对文件路径-Web应用程序档案未扩展?
我该如何解决?
最佳答案
解决方式不同。我以编程方式实例化ClasspathResource
,其路径以META-INF
而不是classpath:
开头