Created
April 19, 2018 06:21
-
-
Save bastman/1ee82d5102a330a739c66179a34f5abe to your computer and use it in GitHub Desktop.
Extensions for binding configuration properties in spring boot (kotlin)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.databind.ObjectMapper | |
import com.fasterxml.jackson.module.kotlin.convertValue | |
import org.springframework.boot.context.properties.bind.Bindable | |
import org.springframework.boot.context.properties.bind.Binder | |
import org.springframework.core.env.Environment | |
/* | |
Example: | |
val stuff:MyAwesomeDataClass = bindEnvironmentProperties( | |
environment = env, | |
name = "example.kotlin", | |
objectMapper = Jackson.defaultMapper() | |
) | |
val stuff:Map<String,Any?> = bindEnvironmentProperties( | |
environment = env, | |
name = "example.kotlin", | |
objectMapper = Jackson.defaultMapper() | |
) | |
val stuff:List<Any?> = bindEnvironmentProperties( | |
environment = env, | |
name = "example.kotlin", | |
objectMapper = Jackson.defaultMapper() | |
) | |
*/ | |
inline fun <reified T : Any> bindEnvironmentProperties( | |
environment: Environment, name: String, objectMapper: ObjectMapper | |
): T { | |
val data: Any = run { | |
try { | |
val asList = Binder.get(environment) | |
.bind(name, Bindable.listOf(Any::class.java)).get() | |
return@run asList | |
} catch (all: Exception) { | |
} | |
try { | |
val asMap = Binder.get(environment) | |
.bind(name, Bindable.mapOf(String::class.java, Any::class.java)).get() | |
return@run asMap | |
} catch (all: Exception) { | |
} | |
} ?: throw RuntimeException( | |
"Failed to convert content of environment.$name to ${T::class.java} !" | |
+ " Expected: environment.$name to be of type Map<String,Any?> or List<Any?>" | |
+ " reason: No value bound" | |
) | |
try { | |
return objectMapper.convertValue(data) | |
//val content = objectMapper.writeValueAsString(data) | |
//return objectMapper.readValue(content, jacksonTypeRef<T>()) | |
} catch (all: Exception) { | |
throw RuntimeException( | |
"Failed to convert content of environment.$name to ${T::class.java} !" | |
+ " content: ${objectMapper.writeValueAsString(data)}" | |
+ " reason: ${all.message}" | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment