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