neXus
neXus

Reputation: 2223

How to set default values for missing environment variables in maven pom

Is it possible to have maven provide default values for missing environment variables? If so, how?


Context:

I have properties files with placeholders to environment variables, like this: my.property=${env:ENVIRONMENT_PROPERTY}

Running maven (edit: not like this mvn ... -DENVIRONMENT_PROPERTY=some_value) if the environment variable is set in the OS makes it resolve the property placeholder with the given value. But if the environment variable does not exist, the value is blank.

Problem:

I would like the environment variables to have a default value. If the environment variable does not exist it should be given a default value that would be specified in the pom or some properties file or whatever.

Important:

The property placeholders have to point to an environment variable.

Upvotes: 1

Views: 10206

Answers (3)

Evgeniy Sidenko
Evgeniy Sidenko

Reputation: 109

You might define a property with a default value.

<your_property default-value="Undefined">${env.environent_variable_name}</your_property>

That's it!
If you define environent_variable_name then your_property will be equal to it; otherwise, the your_property will be equal to Undefined.

Upvotes: 10

neXus
neXus

Reputation: 2223

I used the felix fileinstall plugin (org.apache.felix.fileinstall) This allows the following notation:

${env:ENVIRONMENT_PROPERTY:-default value}

This will take the value from the ENVIRONMENT_PROPERTY and if that is not set, it would take "default value".


EDIT:
If you want to take the default values from maven properties, you need to use the ${dollar} hack:

${dollar}{env:ENVIRONMENT_PROPERTY:-${default.value}}

where dollar is a maven property that is resolved to a dollar symbol (<dollar>$</dollar>) which turns into a delimiter when combined with the { bracket.

Upvotes: 5

mediahype
mediahype

Reputation: 500

The maven resources plugin is your friend. It should already run as part of your build. But it does not filter resources by default. You have to configure that:

  <resource>
     <directory>src/main/resources</directory>
     <filtering>true</filtering>
  </resource>

Then configure a filter:

<build>
   ...
   <filters>
      <filter>my-filter-values.properties</filter>
   </filters>

Put the default values you want into that file. Given the precedence of properties in maven:

(1) command line (2) settings.xml (3) pom.xml (4) filters

The properties in your filter file can act as what you want to have as defaults.

For a proper explanation of filters, consult the official documentation: Filters under the maven-resources-plugin ! (It's here)

Upvotes: 2

Related Questions