Skip to content

Instantly share code, notes, and snippets.

@libetl
Created October 31, 2020 13:21
Show Gist options
  • Save libetl/cb45dccaf27fd68a95fd79e3e02fad75 to your computer and use it in GitHub Desktop.
Save libetl/cb45dccaf27fd68a95fd79e3e02fad75 to your computer and use it in GitHub Desktop.
LoadYaml.kt
package com.mycompany.library.tools
import org.springframework.boot.env.YamlPropertySourceLoader
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.core.env.Profiles
import org.springframework.core.io.ClassPathResource
object LoadYaml {
data class LoadOptions(
val environment: ConfigurableEnvironment?,
val deactivationProfile: String? = null,
val yamlName: String,
val yamlClassPathResource: ClassPathResource,
val forApplicationScopeOnly: Boolean = false,
val checkProfiles: Boolean = false,
val addFirst: Boolean = false
)
infix fun with(options: LoadOptions) {
val (
environment,
deactivationProfile,
yamlName,
yamlClasspathFile,
forApplicationScopeOnly,
checkProfiles,
addFirst
) = options
if (deactivationProfile != null &&
environment?.activeProfiles?.contains(deactivationProfile) != false
) return
if (forApplicationScopeOnly && environment?.propertySources?.contains("bootstrap") != false) return
YamlPropertySourceLoader().load(
yamlName,
yamlClasspathFile
).forEach {
val availableForSpringProfiles = it.getProperty("spring.profiles") as String?
val willCheckProfiles = checkProfiles && availableForSpringProfiles != null
val profiles = if (!willCheckProfiles) null
else Profiles.of(availableForSpringProfiles)
val addAllowed = !willCheckProfiles || environment?.acceptsProfiles(profiles!!) == true
if (addAllowed && addFirst)
environment?.propertySources?.addFirst(it)
else if (addAllowed)
environment?.propertySources?.addLast(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment