我们在 Scala 应用程序中使用 Spring MVC,我想弄清楚如何打开 ScalaOption
这样它们就可以使用正确转换@RequestParam
。我认为解决方案可能与格式化程序 SPI,但我不确定如何让它很好地工作Option
可以包含任意数量的值(我希望 Spring 能够正常处理,就好像转换后的值不是Option
根本没有)。本质上,我几乎想应用一个额外的值转换为Option
正常转换发生后包装。
例如,给出以下代码:
@RequestMapping(method = Array(GET), value = Array("/test"))
def test(@RequestParam("foo") foo: Option[String]): String
The url /test
应该导致foo
参数得到的值为None
,而网址/test?foo=bar
应该导致foo
参数得到的值为Some("bar")
(/test?foo
可能会导致空字符串,或者None
).
我们设法通过创建一个来解决这个问题AnyRef
to Option[AnyRef]
转换器并将其添加到 Spring MVC 中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))
)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)