Wednesday, 23 March 2011

Customise the build using maven profiles and copy-resources plugin

Problem: Need to use different properties per environment.

CopyResourcesTest.java
package com.irenty;

import java.io.InputStream;
import java.util.Properties;

import org.junit.Test;

public class CopyResourcesTest {

    @Test
    public void testHelloWorld() throws Exception {
        InputStream propsStream = CopyResourcesTest.class.getResourceAsStream("/app.properties");
        Properties properties = new Properties();
        properties.load(propsStream);
        System.out.println("my.value=" + properties.getProperty("my.value"));
    }
}

Project structure:
copy-resources
¦   pom.xml
+---src
¦   +---main
¦   ¦   +---resources
¦   ¦       ¦   app.properties
¦   ¦       ¦
¦   ¦       +---configs
¦   ¦           +---custom
¦   ¦           ¦       app.properties
¦   ¦           ¦
¦   ¦           +---prod
¦   ¦                   app.properties
¦   +---test
¦       +---java
¦           +---com
¦               +---irenty
¦                       CopyResourcesTest.java

Program always reads properties from /app.properties that is in src/main/resources. The dafault content of that file is:
my.value=default

There are 2 other files in the resources folder: src/main/resources/custom/app.properties and src/main/resources/prod/app.properties containing:
my.value=custom
and
my.value=prod

Depending on the environment we want to build for different app.properties should be included in the package. To achieve that we will use maven profiles.

Here is the pom.xml for our project.

There are 2 profiles defined: prod and custom. Building with each of them will package the application with corresponding properties.

Here are the test results:
mvn clean install
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.irenty.CopyResourcesTest
my.value=default
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 sec
...
mvn clean install -Pcustom
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.irenty.CopyResourcesTest
my.value=custom
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 sec
...
mvn clean install -Pprod
...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.irenty.CopyResourcesTest
my.value=prod
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 sec
...

Normally in the output package we only need 1 properties file. To do that we exclude the src/main/resources/configs from the resources, so the target folder looks like this:

└───target
    ├───classes
    │       app.properties
    │
    └───test-classes
        └───com
            └───irenty
                    CopyResourcesTest.class

No comments: