所有
我在里面创建了一个包含以下MANIFEST.MF的jar文件:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.6.0_25-b06 (Sun Microsystems Inc.)
Main-Class: my.Main
Class-Path: . lib/spring-core-3.2.0.M2.jar lib/spring-beans-3.2.0.M2.jar
在它的根目录中有一个名为my.config的文件,它在我的spring-context.xml中被引用,如下所示:
<bean id="..." class="...">
<property name="resource" value="classpath:my.config" />
</bean>
如果我运行jar,除了加载特定文件外,一切看起来都很好:
Caused by: java.io.FileNotFoundException: class path resource [my.config] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/work/my.jar!/my.config
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:205)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:52)
at eu.stepman.server.configuration.BeanConfigurationFactoryBean.getObject(BeanConfigurationFactoryBean.java:32)
at eu.stepman.server.configuration.BeanConfigurationFactoryBean.getObject(BeanConfigurationFactoryBean.java:1)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 22 more
从jar内部加载
-
个类
-
spring和其他依赖项从分隔的jar中加载
加载 -
spring上下文(new ClassPathXmlApplicationContext("spring-context/applicationContext.xml"))
-
my.properties加载到PropertyPlaceholderConfigurer("classpath:my.properties")
-
如果我将.config文件放在文件系统之外,并将资源URL更改为'file:',一切似乎都很好......
有小费吗?
4 回答
如果你的spring-context.xml和my.config文件在不同的jar中,那么你需要使用
classpath*:my.config
?更多信息here
此外,从jar文件中加载时,请确保使用
resource.getInputStream()
而不是resource.getFile()
.我知道这个问题已经得到了回答 . 但是,对于那些使用 spring 靴的人来说,这个链接对我有帮助 - https://smarterco.de/java-load-file-classpath-spring-boot/
然而,
resourceLoader.getResource("classpath:file.txt").getFile();
导致了这个问题和sbk的评论:帮助我理解为什么要使用getInputStream() . 它现在适合我!
谢谢!
在spring jar包中,我使用了新的
ClassPathResource(filename).getFile(), which throws the
异常:但是使用新的
ClassPathResource(filename).getInputStream()
将解决这个问题 . 原因是jar中的配置文件不存在于操作系统的文件树中,因此必须使用getInputStream()
.使用Tomcat6.x时我遇到了类似的问题,我发现没有任何建议有帮助 . 最后我删除了
work
文件夹(Tomcat)并且问题消失了 .我知道这是不合逻辑的,但出于文件目的......