Spring MVC - 绑定枚举数组

ara*_*ant 3 data-binding spring-mvc

如果我以格式发布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'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Bha*_*ikh 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以在任何可能需要类型转换的地方使用Converter.现在,您需要做的是注册它:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="package.path.WeatherConverter"/>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

它完成了.

您可以在Spring Reference中查看更多详细信息.

您也可以使用@InitBinder查看PropertyEditor,如果需要,也可以查看@ControllerAdvice.但是,转换器更容易使用(IMO).