简体   繁体   English

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

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

Spring Boot 2.1.5.RELEASE here. Spring 在此处启动 2.1.5.RELEASE。 I'm trying to load a resource from a src/main/resources/images directory.我正在尝试从src/main/resources/images目录加载资源。 My best attempt thus far is:到目前为止,我最好的尝试是:

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

At runtime the WARNing " Hmmm not found... " is printing, but the file is absolutely located at src/main/resources/images/my_logo.png .在运行时,警告“ Hmmm not found... ”正在打印,但该文件绝对位于src/main/resources/images/my_logo.png Where am I going awry?我哪里出错了?

Since you are already using Spring, try using one of their resource loaders由于您已经在使用 Spring,请尝试使用他们的资源加载器之一

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

Notice: I added a leading slash to the path.注意:我在路径中添加了一个前导斜杠。

EDIT : I did check on @duffymo's comment and it was correct.编辑:我确实检查了@duffymo 的评论,它是正确的。 The leading slash is not necessary.前导斜杠不是必需的。

There is also another way to retrieve resources in Spring, but the ResourceUtils Javadoc is clear that the class is mainly for internal use. Spring中还有另一种获取资源的方法,但是ResourceUtils Javadoc明确指出class主要是内部使用。

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

Or by using ClassPathResource或者通过使用ClassPathResource

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

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

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