Monday, August 26, 2013

Use Spring to Load a Resource From the Classpath

The architecure of our projects is such that when I tried to load a resource via a common method call with the traditional this.getClass().getClassLoader().getResourceAsStream(resourcename) it was unable to do so. The resource was in another project which was wired up as a dependency in the webapp.

I knew the resource was on the classpath, but even so I could only load resources from the main project. I'm sure if I played around with it long enough I could get it to work(maybe this), but I never really liked having to get a class loader from an existing class anyways.

In my searching I eventually came across a useful class called the ClassPathResource provided in Spring.  Simply by instantiating a ClassPathResource it seamlessly grabbed the resource I knew was there.

This allowed me to change from reportInputStream = this.getClass().getClassLoader().getResourceAsStream(reportPath); to reportInputStream = new ClassPathResource(reportPath).getInputStream();

No comments:

Post a Comment