Java Spring引导转换枚举忽略大小写
我有一个spring启动应用程序,它公开了一个。此API接受枚举batchStatus列表作为查询参数。此batchStatus用于根据其状态筛选所有批次 当尝试调用这个RESTAPI时,我得到以下错误Java Spring引导转换枚举忽略大小写,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个spring启动应用程序,它公开了一个。此API接受枚举batchStatus列表作为查询参数。此batchStatus用于根据其状态筛选所有批次 当尝试调用这个RESTAPI时,我得到以下错误 { "timestamp": 1552587376808, "status": 400, "error": "Bad Request", "message": "Failed to convert value of type 'java.lang.String[]' to req
{
"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转换服务,我发现了两个转换器
1.弹簧芯的StringToEnumConverterFactory
2.StringToEnumIgnoringCaseConverterFactory从弹簧靴
弹簧靴中是否有强制使用第二个转换器的机制
进一步的调试表明,这两个转换器都已向ConversionService注册,但每个转换器的数量不同。在这种情况下,spring如何选择要使用的转换服务
Enum 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;
}
}
查看Spring项目的问题跟踪程序,您可以找到问题,它基本上要求公开StringToEnumIgnoringCaseConverterFactory类。 然而,这似乎不会很快发生,因为它仍在进行中 您可以尝试通过WebMVCConfigureRadFormatters配置该转换器 ApplicationConversionServiceconfigure将通过调用addApplicationConverters方法为您注册StringToEnumIgnoringCaseConverterFactory
顺便说一句,这是对StringToEnumIgnoringCaseConverterFactory的唯一引用,所以这是您唯一的希望;不要使用反射!忍住冲动谢谢,这很有效。此外,正如中所建议的,最好创建自己的转换器,而不是使用StringToEnumIgnoringCaseConverterFactory@Abhishek我不会走那条路。目前,如果它有效,请坚持使用标准的。
@Configuration
class CustomWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addFormatters(final FormatterRegistry registry) {
ApplicationConversionService.configure(registry);
}
}
/** Spring Framework code */
public static void addApplicationConverters(ConverterRegistry registry) {
...
registry.addConverterFactory(new StringToEnumIgnoringCaseConverterFactory());
}