Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 748
pupeno Avatar asked Sep 09 '17 10:09

pupeno


1 Answers

You can use Gradle's source sets for this:

Sample build.gradle:

apply plugin: 'java'

sourceSets {
    prod {
        java {
            srcDirs = ['src/main/java', 'src/prod/java']
        }
    }
    dev {
        java {
            srcDirs = ['src/main/java', 'src/dev/java']
        }
    }
}

task devJar(type: Jar) {
    from sourceSets.dev.output
    manifest {
        attributes("Main-Class": "MyPackage.MyClass")
    }
}

task prodJar(type: Jar) {
    from sourceSets.prod.output
    manifest {
        attributes("Main-Class": "MyPackage.MyClass")
    }
}

Now you can create two configuration classes for your dev and prod versions: src/dev/java/MyPackage/Configuration.java
src/prod/java/MyPackage/Configuration.java

All the common code will be in the main source set:
src/main/java/MyPackage/MyClass.java

MyClass can get some values from the configuration class (e.g. Configuration.getBaseUrl())

Running gradle devJar/ gradle prodJar builds one of the variants.

Note: you may need to extend jfxNative/jfxJar instead of Jar in your case.

like image 109
dev.bmax Avatar answered Nov 09 '22 11:11

dev.bmax