Question

I would like to set a property in Maven, but also read a sensible default when running the application without Maven.

Currently I have a property file which looks like this:

baseUrl=${baseUrl}

Using the maven-resources-plugin, I can then filter this property, and set it to either the default property in the pom, or overwrite it using -DbaseUrl= from the command line. So far so good.

However, I want to go a step further and set a sensible default to baseUrl in the property file without having to write hacks in code like this (when the code is run without Maven in a Unit Test):

 if ("${baseUrl}".equals(baseUrl)){ /* set to default value */ } 

Even better, I would like this file to be unversioned such that every developer can set their own value. (Actually property files should be hierarchical such that developers only overwrite relevant properties and new properties don't break their build. This is an Android project by the way, and I'm running this code in unit tests)

Was it helpful?

Solution 2

In the end I decided to create a static helper:

public class PropertyUtils {


    public static Properties getProperties(Context context)  {
        AssetManager assetManager =  context.getResources().getAssets();
        Properties properties = new Properties();
        try {
            loadProperties(assetManager, "project.properties", properties);
            if (Arrays.asList(assetManager.list("")).contains("local.properties")){
                loadProperties(assetManager, "local.properties", properties);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return properties;
    }

    private static void loadProperties(AssetManager assetManager, String fileName, Properties properties) throws IOException {
        InputStream inputStream = assetManager.open(fileName);
        properties.load(inputStream);
        inputStream.close();
    }
}

Where project.properties in assets directory has the following property:

baseUrl=${baseUrl} 

and local.properties in assets:

baseUrl=http://192.168.0.1:8080/

local.properties is excluded from version control, and overwrites any project.properties. Thus when building in the CI tool, baseUrl is overridden with relevant value, and when running locally (in IntelliJ), the local.properties value will be used.

OTHER TIPS

Just set the property in the POM, in <properties>. The set value will be used unless you override it by using the -D switch, a profile, etc. In your case this would be:

<properties>
    <baseUrl>some_default_url</baseUrl>
</properties>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top