2015-11-18 57 views
2

我們在我們的Scala應用程序中使用Spring MVC,我想弄清楚如何解開Scala Option's,以便它們可以使用@RequestParam正確轉換。我認爲解決方案可能與Formatter SPI有關,但我不確定如何讓這個工作很好地工作,因爲Option可以包含任何數量的值(我希望Spring能夠正常處理,就好像轉換價值根本不是Option)。實質上,我幾乎想要在正常轉換髮生後應用額外的值轉換爲OptionScala的Spring RequestParam格式器.Option

例如,給定下面的代碼:

@RequestMapping(method = Array(GET), value = Array("/test")) 
def test(@RequestParam("foo") foo: Option[String]): String 

的網址/test應導致foo參數得到的None一個值,而URL /test?foo=bar應當導致foo參數得到的Some("bar")的值( /test?foo可能會導致一個空字符串或None)。

回答

0

我們設法通過創建一個AnyRefOption[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)) 
    ) 
    } 
} 
相關問題