gpt4 book ai didi

Spring 资源加载

转载 作者:行者123 更新时间:2023-12-04 21:14:17 26 4
gpt4 key购买 nike

谁能解释当使用 ResourceLoader.getResource(...) 方法时 Spring 如何决定在哪里寻找资源?
我在使用 Spring Boot 构建的多模块 maven 应用程序时遇到问题,在我的集成测试中,我的代码能够使用 resourceLoader.getResource("templates/") 找到资源甚至resourceLoader.getResource("classpath:templates/") .到现在为止还挺好...
但是,当模块最终打包成可执行 JAR 并与嵌入式 Tomcat 一起运行时,资源将无法再解析。我也试过resourceLoader.getResource("classpath*:templates/")没有成功。
我发现有关的是,当我添加一个日志语句以输出搜索中使用的 URL 时,我得到了项目中其他模块之一的路径(不是实际包含相关资源的模块)。例如:jar:file:/Users/david/exmaple/target/spring-boot-0.0.1-SNAPSHOT.jar!/lib/module1-0.0.1-SNAPSHOT.jar!/templates/而我相信资源在 jar:file:/Users/david/exmaple/target/spring-boot-0.0.1-SNAPSHOT.jar!/lib/module2-0.0.1-SNAPSHOT.jar!/templates/资源加载器是从 Autowired 构造函数参数中获得的。
提前感谢您的任何提示。
编辑
以防万一不清楚或很重要,我对相关模块的集成测试不知道其他模块。我有 module1、module2 和一个依赖于 module1 和 module2 的 spring-boot 模块。本质上,当我为模块 2 运行集成测试时,类路径不知道模块 1 - 所以我怀疑这与它在测试中工作的原因有关。

最佳答案

当您使用 classpath:classpath*:前缀,在内部,这基本上是通过 Spring 中的 ClassLoader.getResources(...​) 调用发生的。

The wildcard classpath relies on the getResources() method of the underlying classloader. As most application servers nowadays supply their own classloader implementation, the behavior might differ especially when dealing with jar files. A simple test to check if classpath* works is to use the classloader to load a file from within a jar on the classpath: getClass().getClassLoader().getResources("<someFileInsideTheJar>"). Try this test with files that have the same name but are placed inside two different locations. In case an inappropriate result is returned, check the application server documentation for settings that might affect the classloader behavior.



不要使用 classpath:表单,因为您有多个 templates/ 的类加载器位置.

引用: resources-classpath-wildcards

关于Spring 资源加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com