Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
spring conversion helpers for scala
package com.solarmosaic.core.service.converter
import javax.inject.Inject
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.core.convert.{TypeDescriptor, ConversionService}
import scala.reflect._
/**
* Converts from type `A` to type `B` using the given ConversionService.
*
* @param from The object to convert from.
* @param conversionService The ConversionService
* @tparam A Type to convert from
*/
class Conversion[A: ClassTag](from: A, conversionService: ConversionService) {
/**
* Performs conversion from type `A` to type `B`.
*
* @tparam B The type to convert to.
* @return An instance of the class we are converting to.
*/
def convertTo[B: ClassTag]: B = {
val sourceType = classTag[A].runtimeClass.asInstanceOf[Class[A]]
val targetType = classTag[B].runtimeClass.asInstanceOf[Class[B]]
conversionService
.convert(from, TypeDescriptor.valueOf(sourceType), TypeDescriptor.valueOf(targetType))
.asInstanceOf[B]
}
}
/**
* Extend this trait to provide automatic conversions inside your class.
*/
trait Conversions {
import scala.language.implicitConversions
/**
* Provides a `ConversionService` for use inside REST controllers. This needs to be qualified specifically for
* use by Spring MVC to prevent collisions with other `ConversionService` objects Spring boot supplies automatically.
*/
@Inject
@Qualifier("mvcConversionService")
var conversionService: ConversionService = _
/**
* Implicitly provide conversions for the given type `A`.
*
* @param from The object to convert from.
* @tparam A The type of the object.
* @return The Conversion class for type `A`.
*/
implicit def toConversion[A: ClassTag](from: A): Conversion[A] = new Conversion[A](from, conversionService)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment