maven – configuration for properties file

The desired requirements are the following:

  1. Output should be a JAR
  2. There must exist at least one properties file (e.g. config.properties). All properties files should not be placed inside the JAR, but should be easily accessible by the user.
  3. It should be easy to add more properties files without changing pom.xml

To address the requirements above we have to do the following steps:

  1. We create and place the properties file in src/main/resources
  2. To copy the properties file in the target directory upon build,  we add an include rule to the resources section.
  3. To create the JAR file, we use the maven-jar-plugin
    1. We should exclude properties files from the JAR build
    2. We should define the main class for the JAR so that it is executable
  4. We should copy the properties files from the resources directory to the target directory
  5. We should change the code to read the properties file from the classpath

To load the properties, we can use the following code:

Properties prop = new Properties();
prop.load(getClass().getResourceAsStream("/config.properties"));

 

Example of the pom.xml:

 <build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-resources-plugin</artifactId>
      <version>2.7</version>
      <executions>
        <execution>
        <id>copy-resources</id>
        <phase>install</phase>
        <goals>
          <goal>copy-resources</goal>
        </goals>
        <configuration>
          <outputDirectory>${basedir}/target</outputDirectory>
          <resources>
            <resource>
            <directory>src/main/resources</directory>
            <includes>
              <include>**/*.properties</include>
            </includes>
            </resource>
          </resources>
        </configuration>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <!-- Build an executable JAR -->
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.0.2</version>
      <configuration>
        <excludes>
          <exclude>**/*.properties</exclude>
        </excludes>
        <archive>
        <manifest>
          <addClasspath>true</addClasspath>
          <classpathPrefix>lib/</classpathPrefix>
          <mainClass>com.blabla.MyMainClass</mainClass>
        </manifest>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>

 

 

Advertisements