Including resources in Maven projects

From JQuantLib

Jump to: navigation, search

When using m2eclipse plugin [for Eclipse], you may find troubles trying to load resources in your applications. This article explains why it happens and exposes ways to circunvent this problem. Richard Gomes


Contents

The problem: getResourceAsStream fails

When you are using m2eclipse what you have in your resources directory are not copied to the classpath by default. It happens intentionally because the Maven build lifecycle is responsible for processing your resources, eventually filtering them, etc. You can find a little more information about it here.

When you are running your application inside Eclipse what happens is that the Maven build lifecycle runs only partially and those steps responsible for processing your resources do not run, which end up not copying any resources to the classpath :(

So, if you are trying to read something from your resources directory like shown below, a NPE will be thrown because getResourceAsStream was not able to find the resource in the classpath.

final InputStream is = this.getClass().getResourceAsStream("/myresource.txt");
final InputStreamReader isr = new InputStreamReader(is); // throws NPE :(


The easy solution

The easiest (and probably wrong!) solution for it would be tell Eclipse to not exclude resources from /src/main/resources.
As far as I understood, m2eclipse is the culprit for this behavior, telling Eclipse IDE that /src/main/resources should have all resources excluded by default. (I'm not plenty sure of this!) Well (and anyway...), I suppose that designers of m2eclipse had a very good reason for doing this and I wouldn't like to disagree with them.


A better solution

I decided to add an additional resources folder which Eclipse IDE does not attempt to exclude anything. It's just a matter of adding another resource folder with the default parameters. The image below shows the src/main/resources as it was originally created and an additional /src/main/raw-resources which I created for keeping my beloved resouces which should be copied to the classpath as I expected since the beggining.


IMAGE NEEDS TO BE ADDED


Inside Eclipse I can run my application and it works as expected :)


Running from the command line

The downside is that when I generate my application using a Maven script (pom.xml), I need to remember to copy /src/main/raw-resources to the classpath myself. So, I need to add something to the pom.xml file at some point. As soon as I have done this I will update this article. So, click on the watch tab to be notified when I do so.


References


Richard Gomes 14:25, 15 November 2009 (UTC)