I am trying to run a very simple Spring Boot application with PostGreSQL, which has the application.properties defined as follows:
datasource.username=${PG_USER}
datasource.password=${PG_PASSWD}
datasource.driverClassName=org.postgresql.Driver
datasource.url=jdbc:postgresql://${PG_HOST}:${PG_PORT}/${PG_DATABASE}?currentSchema=${PG_SCHEMA}
I am using gradle bootRun to build and start the project. I have tried to define the environment variables in the IntelliJ run config, but the program still fails in the startup to access the variables. I have tried to setup my build.gradle as follows
bootRun{
workingDir("..")
systemProperties = System.properties
environment = [
MY_CLUSTER: "dev",
MY_NAMESPACE: "dev"...
]
}
but it still has the same results. I have also tried directly reading the variables from the System.properties as shown below, but the variables still turn out to be nulls.
bootRun{
workingDir("..")
systemProperties = System.properties
environment = [
PG_PASSWD: System.getProperty("PG_PASSWD"),
PG_PORT: System.getProperty("PG_PORT"),
PG_SCHEMA: System.getProperty("PG_SCHEMA"),
PG_HOST: System.getProperty("PG_HOST"),
PG_DATABASE: System.getProperty("PG_DATABASE"),
PG_USER: System.getProperty("PG_USER"),
MY_CLUSTER: "dev",
MY_NAMESPACE: "dev"...
]
}
The only option that has so far worked for me is this, which probably is not that great since the local variables are injected directly into the build.gradle which is part of the code
bootRun{
workingDir("..")
environment = [
PG_PASSWD: "postgres",
PG_PORT: "5432",
PG_SCHEMA: "public",
PG_HOST: "localhost",
PG_DATABASE: "postgres",
PG_USER: "postgres",
MY_CLUSTER: "dev",
MY_NAMESPACE: "dev"
]
}
Question: Is there a way we can just define the environment variables in the IntelliJ run configuration and let the bootRun read from there?
Thanks a lot, Prabal
CodePudding user response:
2 levels of indirection is needed for gradle boot run property setup - with out adding to the project gradle.properties
- define the real values in your ${GRADLE_USER_HOME}/gradle.properties (GRADLE_USER_HOME is usually ${HOME}/.gradle) in this file you define properties - global
PG_PASSWD="postgres"
PG_PORT="5432"
PG_SCHEMA="public"
PG_HOST="localhost"
PG_DATABASE="postgres"
PG_USER: "postgres",
MY_CLUSTER: "dev",
MY_NAMESPACE: "dev"
- in your project build.gradle - the above now accessible as properties
bootRun{
workingDir("..")
environment = [
PG_PASSWD: "$PG_PASSWD",
PG_PORT: "$PG_PORT",
PG_SCHEMA: "$PG_SCHEMA",
PG_HOST: "$PG_HOST",
PG_DATABASE: "$PG_DATABASE",
PG_USER: "$PG_USER",
MY_CLUSTER: "$MY_CLUSTER",
MY_NAMESPACE: "$MY_NAMESPACE"
]
}
this will be sufficient for gradle bootRun.
Note: if you are running (spring boot App) in the IntelliJ directly - the properties must be defined in the Run/Debug.