I have a multi-module Spring Boot Gradle project (Kotlin) with the following directory structure.
root
|- domain (Module containing entities and interfaces)
|- application (Spring boot Kotlin application)
|- src/main
|- kotlin (app sources)
|- resources
|- application.properties (default config)
|- src/test/kotlin/long/package/name/ApplicationTests.kt
|- build.gradle.kts (and also gradle folder)
|- config
|- application.properties (config to override classpath properties)
|- build.gradle.kts (and settings.gradle.kts and other gradle folder)
When I run the Application.kt
file, it is able to pick up this file (both with IDE and gradle), and it runs successfully.
Since my config folder is outside my application folder, running my ApplicationTests.kt
results in the error below. The output is same when running through IDE (IntelliJ) run button and ./gradlew clean test
.
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection
I am expecting the tests to find the application.properties
file inside the config folder. How can I register my config/application.properties so that I can keep it separate from my classpath:application.properties
?
UPDATE: I tried adding the following copy task to gradle.
tasks.create("copy", Copy::class.java) {
from("../config")
into("$buildDir/resources/main")
}
tasks.named("test").configure {
dependsOn("copy")
}
This enables me to overwrite the application.properties from config folder (meaning any property not added in config/app.prop is no longer present). Test runs successfully now (if I add all entries from classpath properties to config/app.props). How can I merge the contents of these two properties files inside application/build.gradle.kts
?
CodePudding user response:
By default, Spring will look in your current working directory for the directory named, config
. As you've noted, you're not executing the application in the directory containing the config
directory. You can override where Spring looks for this config
folder with the -Dspring.config.location
option or via the environment variable, SPRING_CONFIG_LOCATION
If your config directory is located at /opt/myconfigs/config
, you would start your service with -Dspring.config.location=/opt/myconfigs/config
. Another option is to export SPRING_CONFIG_LOCATION=/opt/myconfigs/config
and start your app without any additional JVM options.
CodePudding user response:
If you want to override your application.properties
with an external application.properties
, you can copy the external file to build/classes
directory using Gradle and append a profile name, like application-ext.properties
. Then, activate default
and ext
profiles using spring.profiles.active
.
Another option would be to use Spring Config server, but that may be overkill for this simple task.