用于Scala.Option的Spring RequestParam格式化程序 [英] Spring RequestParam formatter for Scala.Option
问题描述
我们在Scala应用程序中使用Spring MVC,我想弄清楚如何解包Scala Option
,以便可以使用@RequestParam
正确转换它们.我认为该解决方案可能与格式化程序SPI ,但是由于Option
可以包含任意数量的值(我希望Spring正常处理,就像转换后的值根本不是Option
).从本质上讲,我几乎想在正常转换发生后将值的附加转换应用为Option
包装.
We are using Spring MVC in our Scala application and I would like to figure out how to unwrap Scala Option
's so they can be properly converted using @RequestParam
. I think the solution may have something to do with the Formatter SPI, but I am unsure how to get this to work nicely given that Option
's can contain any number of values (which I'd want Spring to handle normally, as if the converted value were not an Option
at all). In essence, I'd almost want to apply an additional conversion of a value to be Option
wrapped after normal conversion takes place.
例如,给出以下代码:
@RequestMapping(method = Array(GET), value = Array("/test"))
def test(@RequestParam("foo") foo: Option[String]): String
url /test
应该导致foo
参数获得None
的值,而url /test?foo=bar
应该导致foo
参数获得Some("bar")
的值(/test?foo
可以结果为空字符串或None
.
The url /test
should result in the foo
parameter getting a value of None
, while the url /test?foo=bar
should result in the foo
parameter getting a value of Some("bar")
(/test?foo
could result in either an empty String, or None
).
推荐答案
我们通过创建一个AnyRef
到Option[AnyRef]
转换器并将其添加到Spring MVC的ConversionService
:
We managed to solve this by creating an AnyRef
to Option[AnyRef]
converter and adding it to Spring MVC's ConversionService
:
import org.springframework.beans.factory.annotation.{Autowired, Qualifier}
import org.springframework.core.convert.converter.ConditionalGenericConverter
import org.springframework.core.convert.converter.GenericConverter.ConvertiblePair
import org.springframework.core.convert.{ConversionService, TypeDescriptor}
import org.springframework.stereotype.Component
import scala.collection.convert.WrapAsJava
/**
* Base functionality for option conversion.
*/
trait OptionConverter extends ConditionalGenericConverter with WrapAsJava {
@Autowired
@Qualifier("mvcConversionService")
var conversionService: ConversionService = _
}
/**
* Converts `AnyRef` to `Option[AnyRef]`.
* See implemented methods for descriptions.
*/
@Component
class AnyRefToOptionConverter extends OptionConverter {
override def convert(source: Any, sourceType: TypeDescriptor, targetType: TypeDescriptor): AnyRef = {
Option(source).map(s => conversionService.convert(s, sourceType, new Conversions.GenericTypeDescriptor(targetType)))
}
override def getConvertibleTypes: java.util.Set[ConvertiblePair] = Set(
new ConvertiblePair(classOf[AnyRef], classOf[Option[_]])
)
override def matches(sourceType: TypeDescriptor, targetType: TypeDescriptor): Boolean = {
Option(targetType.getResolvableType).forall(resolvableType =>
conversionService.canConvert(sourceType, new Conversions.GenericTypeDescriptor(targetType))
)
}
}
这篇关于用于Scala.Option的Spring RequestParam格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!