I need to read and filter a properties file from a location outside my project, say ${user.home}/my.properties. This properties file looks like this:
res.dir=/my/stuff/here
resource.dir=C:/${res.dir}
bin.dir=${resource.dir}/bin
cfg.dir=${resource.dir}/config
I have to do this in both my build and in my application when it runs. This is easy to do in Ant, using the PROPERTY tag. However, there doesn't seem to be a good way to do it in Maven.
So far I have tried the Maven <property>
tag, the Maven <filter>
tag and various permutations of other tags. Either my build fails or the unit tests fail, or both.
If I hardcode these properties into the POM, everything works, so I know the problem is just reading the properties.
I looked at the properties-maven-plugin but the plugin no longer seems to be maintained.
Is there a way to do this?
You could simply implement your own
maven-plugin
that will take care of this for you.Here is an example with the following structure:
You will need to create a Mojo that takes the properties file as an input and then propagates the properties to the
pom.xml
of theapp
. Thepom.xml
will actually not be updated but just the project data in it.pom.xml
plugin/pom.xml
plugin/src/main/java/com/stackoverflow/Q12082277/plugin/PropertiesMojo.java
You will use this plugin from the following
app/pom.xml
And then you will have to add the following
app.properties
that will work as a template and take the values that we have just read from file and set them and create a concrete fileapp.properties
that will be reachable from within the jar.app/src/main/resources/app.properties
And finally here is a test application that just loads the
app.properties
from the classpath and prints the result.app/src/main/java/com/stackoverflow/Q12082277/App.java
Now you can stand in the top directory and execute
Then go down into the
app
folder and executeAnd it will print
Which is exactly what you wanted.
I think it would be better if you turned the properties file into a template file and take the properties from the
pom.xml
using maven resource filtering.A simple setup might look like this
pom.xml
src/main/resources/app.properties
src/main/java/com/stackoverflow/Q12082277/App.java
System.out
The
pom.xml
will have the default properties that are used by everybody.If you want to override the values then call maven with input parameters:
System.out
By doing it this way everybody will have the same view of the properties and you can override them if you want to when running on your own machine.