gpt4 book ai didi

spring-mvc - Spring MVC - 绑定(bind)枚举数组

转载 作者:行者123 更新时间:2023-12-04 00:09:41 26 4
gpt4 key购买 nike

如果我以 weather=sunny 格式发布,Spring MVC 会很乐意将其转换为使用名称为 sunny 的枚举的 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'

我怎样才能做到这一点?

最佳答案

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

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 s 任何你可能想要类型转换的地方。现在,您需要做的就是注册它:

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

完成了。

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

您还可以查看 PropertyEditor s,与@InitBinder ,并且可能是 @ControllerAdvice如果你想。然而,Converters更易于使用 (IMO)。

关于spring-mvc - Spring MVC - 绑定(bind)枚举数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16695542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com