jar 中的文件在 spring 中不可见

新手上路,请多包涵

全部

我创建了一个包含以下 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 更改为“文件:”,一切似乎都很好……

有小费吗?

原文由 BTakacs 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 721
2 个回答

如果您的 spring-context.xml 和 my.config 文件位于不同的 jar 中,那么您将需要使用 classpath*:my.config

更多信息 在这里

此外,确保您使用的是 resource.getInputStream() 而不是 resource.getFile() 从 jar 文件中加载时。

原文由 sbk 发布,翻译遵循 CC BY-SA 3.0 许可协议

在spring jar包中,我使用new ClassPathResource(filename).getFile() ,抛出异常:

无法解析为绝对文件路径,因为它不驻留在文件系统中:jar

但是使用 new ClassPathResource(filename).getInputStream() 将解决这个问题。原因是jar中的配置文件在操作系统的文件树中不存在,所以必须使用 getInputStream()

原文由 taozi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题