hi, i'd like to be able to reduce boilerplate for ...
# community-support
g
hi, i'd like to be able to reduce boilerplate for our
JavaExec
tasks by presetting some properties like system properties, env properties, classpath, etc, and i am wondering what's the best way for for it would be. these values need to be different based on which environment we want to run in. i have come up with something like this:
Copy code
abstract class ExecInStaging : JavaExec() {
    init {
        systemProperty("appconfig", "config/staging.properties")
        systemProperty("log4j.configurationFile", "log4j2-local.xml")

        environment("CONSUL_HOST", STAGING_CONSUL)

        classpath = project.extensions
            .getByType<JavaPluginExtension>()
            .sourceSets
            .getByName("main")
            .runtimeClasspath
    }
}
this works - but i am wondering if there are some best practices around this that i am missing? doing all this configuration in the constructor feels a bit weird - especially since now i am getting a bunch of IDE warnings due to
Calling non-final function {} in constructor
... is there a better way to do this?
p
Do it in your plugin when registering your task or using tasks.withType.configureEach
v
Idiomatically - as you gut feeling told you - tasks should optimally be free of opinion but just implement logic, and as Philip said, then usually a plugin adds the opinion by setting convention plugins and wiring extension properties and task properties together. But you could also do it in the constructor, those IDE warnings can be ignored for these cases, as you know that the Gradle generated implementation of these methods is safe to be called from the constructor.
t
Fwiw, unless you really want it to be a
JavaExec
, I'd rather make it a
DefaultTask
with an injected `ExecOperations`.
👍 1
g
yeah, the idea here is to create multiple base tasks that are opinionated in different ways, and just having a plugin that sets them does not sound feasible, because in the same project we would need to be able to use the different environments easily. @Vampire - thank for confirming that even if it feels icky, using the constructor is not a huge mistake 🙂