【发布时间】:2019-08-05 18:43:53
【问题描述】:
我有一个暴露 Rest API 的 spring-boot 应用程序。此 API 接受枚举列表 batchStatus 作为查询参数。这个batchStatus 用于根据批次的状态过滤所有批次。
当尝试调用这个 rest api 时,我收到以下错误
{
"timestamp": 1552587376808,
"status": 400,
"error": "Bad Request",
"message": "Failed to convert value of type 'java.lang.String[]' to required type 'java.util.List'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiParam @javax.validation.Valid @org.springframework.web.bind.annotation.RequestParam com.netshell.test.spring.conversion.rest.api.model.BatchStatus] for value 'active'; nested exception is java.lang.IllegalArgumentException: No enum constant com.netshell.test.spring.conversion.rest.api.model.BatchStatus.active",
"path": "/batch/status"
}
Spring 在 BatchStatus 中寻找 active 而不是 ACTIVE。
深入了解 spring ConversionService 我发现了两个转换器
1. StringToEnumConverterFactory(来自 spring-core)
2. StringToEnumIgnoringCaseConverterFactory(来自spring-boot)
spring-boot 中是否有任何机制强制使用第二个转换器?
进一步调试显示,这两个转换器都注册到 ConversionService,但是有 multiple instances of conversionService 每个转换器的数量不同。这种情况下spring如何选择使用哪个conversionService呢?
枚举BatchStatus创建如下
public enum BatchStatus {
ACTIVE("active"),
FAILED("failed"),
HOLD("hold");
private String value;
BatchStatus(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static BatchStatus fromValue(String text) {
for (BatchStatus b : BatchStatus.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
【问题讨论】:
标签: java spring spring-boot