Search code examples
javaspring-bootclassloader

Loading nested resource from the classpath in Spring Boot


Spring Boot 2.1.5.RELEASE here. I'm trying to load a resource from a src/main/resources/images directory. 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. Where am I going awry?


Solution

  • Since you are already using Spring, try using one of their resource loaders

    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. The leading slash is not necessary.