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
// Copyright ©2025 Jim Hamilton. All rights reserved.
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component
@Component
object SpringContext : ApplicationContextAware {
private lateinit var appContext: ApplicationContext
override fun setApplicationContext(applicationContext: ApplicationContext) {
appContext = applicationContext
}
fun <T> getBean(clazz: Class<T>): T {
return appContext.getBean(clazz)
}
}
Usage:
val mapper = SpringContext.getBean(ObjectMapper::class)
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