A Spring component that allows non-components to load beans; SpringContext implements ApplicaitonContextAware to get the context, then implements a method in its companion object to allow loading a bean. Based on a Java component of the same name byJay Ta'ala: https://me.jaytaala.com/super-simple-approach-to-accessing-spring-beans-from-non-spring-managed-classes-and-pojos but re-written and simplified for Kotlin.
/*
* Copyright © 2025 Jim Hamilton.
* All rights reserved.
*/
import org.springframework.beans.factory.getBean
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
@Component
class SpringContext(val context: ApplicationContext) {
init {
instance = this
}
companion object {
lateinit var instance: SpringContext
inline fun <reified T : Any> getBean(): T = instance.context.getBean()
}
}
Usage:
val mapper = SpringContext.getBean<ObjectMapper>()
or
val mapper: ObjectMapper = SpringContext.getBean()
An extension method to round a double to any desired number of decimal places–including a negative number. Rounding to 2 places will round to the nearest hundredth; rounding to -2 places will round to the nearest hundred.
// Copyright ©2025 Jim Hamilton. All rights reserved.
import kotlin.math.pow
import kotlin.math.round
fun Double.round(decimals: Int): Double {
val multiplier = 10.0.pow(decimals)
return round(this * multiplier) / multiplier
}
Usage:
import kotlin.math.PI
val pi = PI.round(4) // 3.1416
val thousandPi = (1000.0*PI).round(-1) // 3140
Copyright © 2019-2026 Jim Hamilton - All Rights Reserved.