繁体   English   中英

从 Spring 引导中的类路径加载嵌套资源

[英]Loading nested resource from the classpath in Spring Boot

Spring 在此处启动 2.1.5.RELEASE。 我正在尝试从src/main/resources/images目录加载资源。 到目前为止,我最好的尝试是:

URL url = getClass().getResource("classpath:images/my_logo.png");
if (url == null) {
  log.warn("Hmmm not found...");
} else {
  log.info("Found it!");
}

在运行时,警告“ Hmmm not found... ”正在打印,但该文件绝对位于src/main/resources/images/my_logo.png 我哪里出错了?

由于您已经在使用 Spring,请尝试使用他们的资源加载器之一

URL url = new PathMatchingResourcePatternResolver( null ).getResource( "classpath:/images/my_logo.png" ).getURL();

注意:我在路径中添加了一个前导斜杠。

编辑:我确实检查了@duffymo 的评论,它是正确的。 前导斜杠不是必需的。

Spring中还有另一种获取资源的方法,但是ResourceUtils Javadoc明确指出class主要是内部使用。

String file = ResourceUtils.getFile("images/my_logo.png").getAbsolutePath();

或者通过使用ClassPathResource

URL clsPath =  new ClassPathResource("images/my_logo.png").getURL();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM