Spring MVC - 绑定枚举数组

时间:2013-05-22 15:16:15

标签: spring-mvc data-binding

如果我以weather=sunny格式发布,Spring MVC会使用name = sunny的enum将其转换为Weather枚举实例。

但是如果我发布weather=sunny&weather=windy,那么Spring无法将其转换为Weather []的实例。我得到的错误是:

Failed to convert property value of type 'java.lang.String[]' to required type 'com.blah.Weather[]' for property 'weather'

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:5)

您可以使用Converter来执行自定义转换。对于您的示例,您需要执行以下操作:

public class WeatherConverter implements Converter<String[], Weather[]> {

    @Override
    public Weather[] convert(String[] source) {
        if(source == null || source.length == 0) {
            return new Weather[0];
        }
        Weather[] weathers = new Weather[source.length];
        int i = 0;
        for(String name : source) {
            weathers[i++] = Weather.valueOf(name); 
        }
        return weathers;
    }

}

您可以在任何可能需要类型转换的位置使用Converter。现在,您需要做的就是注册它:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="package.path.WeatherConverter"/>
        </list>
    </property>
</bean>

已经完成了。

您可以在Spring Reference

中查看更多详情

您还可以使用PropertyEditor查看@InitBinder,如果需要,也可以查看@ControllerAdvice。但是,Converters更容易使用(IMO)。