5

Using Maven, is it possible to override a Java constant?

Imagine I have

public static final String buildBy="Eclipse";

which when using Maven shall be changed to

public static final String buildBy="Maven";

Is that possible? Thanks :-)

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

3 Answers3

4

Yes this is possible with filters. But you'd have to put the file under your resource directory. You could put the java file under the resource directory, but a much better way would be to extract the value into a property file, put that file under resources and have maven filter the property file.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 1
    move the changing constants to the properties file. The developer who'll maintain your code after you will thank you. – WeMakeSoftware Apr 29 '13 at 20:49
  • 1
    Yes, and if you think about it it should go there. This isn't really a `static final` value. It changes depending on how you build the product. – Daniel Kaplan Apr 29 '13 at 20:51
  • 1
    Thanks for all answers, got it workingusing Resources and filters. A nice example can be found here: http://stackoverflow.com/questions/16287053/scene-getstylesheets-add-not-working-inside-jar-file/16287238 – stefan.at.kotlin Apr 30 '13 at 17:28
  • I need to use them as attributes so they really must be final. – Roel Jul 04 '16 at 11:03
  • This is no solution if it really need to be constants. Like when they are used in attributes values. – Roel Jul 04 '16 at 11:13
2

The other possibility is to use the templating maven plugin which can be used to fulfill such purposes.

Alexey
  • 9,197
  • 5
  • 64
  • 76
khmarbaise
  • 92,914
  • 28
  • 189
  • 235
  • Do you have an example of the usage? I did everything according to the documentation but because the Constants.java file is not generated. The build fails and Intellij also can't find this file. How to reference it if it will be generated? – Roel Jul 04 '16 at 11:24
  • Aha I had to manually run the plugin maven build "templating:filter-sources" – Roel Jul 04 '16 at 11:28
  • https://github.com/khmarbaise/version-examples/tree/master/version-example-iv http://blog.soebes.de/blog/2014/01/02/version-information-into-your-appas-with-maven/ – khmarbaise Jul 04 '16 at 11:31
  • Thanks, I will look at that example. I don't want to manually start the build task because then the risk still remains that someone deploys the dev configuration on production for example. The task templating:filter-sources has to be allways called on build. – Roel Jul 04 '16 at 11:52
0

This is kind of Properties and should go to resource directory /src/main/resources where can be easily changed by maven (filtered).

Read also: Reading Properties file in Java

Community
  • 1
  • 1
MariuszS
  • 30,646
  • 12
  • 114
  • 155