What's the proper way to have various URL endpoints for dev and release in a Java application?

pupeno :

I'm building a Java desktop application, using JavaFX, Gradle, javafx-gradle-plugin. This application connects to a server that I also build. When I compile a release version, running gradle jfxNative, I want it to talk to the production server; but otherwise, I want it to talk to localhost.

What's the proper Java/Gradle way of handling this? Some sort of compilation profile?

highstakes :

The simplest solution: Have a configuration file containing such information. You either compile it into the application as a java resource or place it next to the jar file so it can be easily looked up via the filesystem.

With gradle all you need to do is define two build tasks with different input properties and insert the values into your properties file with groovy templating.

application.properties in src/main/resources:

server.address=${serverAddress}

add to your build.gradle

task setProductionServerAddress {
    processResources.expand([serverAddress: "https://app.example.com/v1"])
}
jfxJar.dependsOn(setProductionServerAddress)
jfxNative.dependsOn(setProductionServerAddress)

And then on the application:

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/application.properties"));
if (properties.getProperty("server.address").equals("${serverAddress}")) {
  setUrl("http://localhost:8080/v1");
} else {
  setUrl(properties.getProperty("server.address"));
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433238&siteId=1