Maven : add external resources

GournaySylvain picture GournaySylvain · Oct 31, 2014 · Viewed 18.8k times · Source

I am building an executable jar file with maven, meaning that you run it with "java -jar file.jar".

I want to rely on user defined properties (just a file containing keys/values), during developpement phase I was putting my "user.properties" file in maven /src/main/resources/ folder.

My property file is loaded with:

final Properties p = new Properties();
final InputStream resource = IOParametres.class.getResourceAsStream("/user.properties");
p.load(resource);

Now, I want to keep that file outside of the JAR and have something like this :

- execution_folder
   |_ file.jar
   |_ config
      |_ user.properties

I tried many things with maven plugins like maven-jar-plugin, maven-surefire-plugin and maven-resources-plugin but I can't get it working...

Thanks in advance for your help!

Answer

GournaySylvain picture GournaySylvain · Nov 3, 2014

I found what I needed using only maven configuration.

First I add config folder to the classpath:

<build>
<plugins>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3.1</version>
    <configuration>
        <archive>
            <manifestEntries>
                <Class-Path>config/</Class-Path>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>
</plugins>
</build>

I load resources the same way as before:

final InputStream resource = IOParametres.class.getResourceAsStream("/user.properties");
p.load(resource);

And if you want to keep your example resource files in your repo and remove them from your build:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>user.properties</exclude>
                <exclude>conf/hibernate.cfg.xml</exclude>
            </excludes>
        </resource>
    </resources>
</build>

Next to the jar file, I add a config folder holding all the resource files I need.

The result is:

  • user.properties can be loaded using getResourceAsStream
  • other libraries relying on specific resources (I won't argue, but I find it... not that good) can load their resources without any issue.

Thanks for the help, and I hope it may help somebody someday!