29

How can I change a .properties file in maven depending on my profile? Depending on whether the application is built to run on a workstation or the datacenter parts of the file my_config.properties change (but not all).

Currently I manually change the .properties file within the .war file after hudson builds each version.

benstpierre
  • 32,833
  • 51
  • 177
  • 288
  • can you please review, https://stackoverflow.com/questions/51186963/value-from-maven-profile-properties-is-not-getting-used-in-properties-file – vikramvi Jul 05 '18 at 13:03

1 Answers1

71

As often, there are several ways to implement this kind of things. But most of them are variations around the same features: profiles and filtering. I'll show the most simple approach.

First, enable filtering of resources:

<project>
  ...
  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    ...
  </build>
</project>

Then, declare a place holder in your src/main/resources/my_config.properties, for example:

myprop1 = somevalue
myprop2 = ${foo.bar}

Finally, declare properties and their values in a profile:

<project>
  ...
  <profiles>
    <profile>
      <id>env-dev</id>
      <activation>
        <property>
          <name>env</name>
          <value>dev</value>
        </property>
      </activation>
      <properties>
        <foo.bar>othervalue</foo.bar>
      </properties>
    </profile>
    ...
  </profiles>
</project>

And run maven with a given profile:

$ mvn process-resources -Denv=dev
[INFO] Scanning for projects...
...
$ cat target/classes/my_config.properties 
myprop1 = somevalue
myprop2 = othervalue

As I said, there are variation around this approach (e.g. you can place values to filter in files), but this will get you started.

References

More resources

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • 3
    If using `Spring Boot` thins would be slightly different. https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html – Shihe Zhang Jul 04 '18 at 08:39
  • I couldn't get it working, can you please check https://stackoverflow.com/questions/51186963/value-from-maven-profile-properties-is-not-getting-used-in-properties-file – vikramvi Jul 05 '18 at 08:50
  • Works perfectly for me! I configured sentry.io with this thanks for that :D – Pwnstar Apr 16 '20 at 09:25