Jim H
Jim H
  • Home
  • Resume
  • Code Review-BestPractices
  • Java Best Practices
  • Kotlin Best Practices
  • Homophones in English
  • Personal
  • Blog

Appendix: Code Snippets

Back to Contents


SpringContext

Double.round(decimals: Int): Double


SpringContext

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.
*/

package xyz.jimh.souschef.config

import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component

/**
* Object that allows a non-bean to access a bean.
*/
@Component
object SpringContext : ApplicationContextAware {

   private lateinit var appContext: ApplicationContext

   /**
    * Called automatically at app startup to supply the [ApplicationContext]
    */
   override fun setApplicationContext(applicationContext: ApplicationContext) {
       appContext = applicationContext
   }

   /**
    * Returns a bean by its class [clazz].
    *
    * @throws UninitializedPropertyAccessException if applicationContext is not
    * initialized (we could check that, and throw a different exception, but
    * that does not really buy anything)
    */
   fun <T> getBean(clazz: Class<T>): T {
       return appContext.getBean(clazz)
   }
}


Usage: 

    val mapper = SpringContext.getBean(ObjectMapper::class.java)

Double.round(decimals: Int): Double

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

First PagePreviousHome

Copyright © 2019-2025 Jim Hamilton - All Rights Reserved.

Powered by

This website uses cookies.

We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.

DeclineAccept