hotmeatballsoup
hotmeatballsoup

Reputation: 605

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?

Upvotes: 0

Views: 1106

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40048

There is also another way to retrieve resources in Spring, but the ResourceUtils Javadoc is clear that the class is mainly for internal use.

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

Or by using ClassPathResource

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

Upvotes: 0

Chris Savory
Chris Savory

Reputation: 2755

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.

Upvotes: 5

Related Questions