我有下面的枚举声明
public enum FamilyType {
FIRSTNAME("firstname"),
LASTNAME("lastname");
private final String type;
FamilyType(String type) {
this.type = type;
}
public static FamilyType fromString(String type) {
for (FamilyType t : FamilyType.values()) {
if (t.type.equals(type)) {
return t;
}
}
return converter(type);
}
@Deprecated
private static FamilyType converter(String value) {
if ("NICKNAME".equalsIgnoreCase(value)) {
return FIRSTNAME;
}
if ("SURENAME".equalsIgnoreCase(value)) {
return LASTNAME;
}
throw new InvalidFileNameException("my-enum", value);
}
}
我有一个控制器端点,其中delete请求保存 FamilyType
作为 Requestparam
如下所示
public String deleteFamilyType(@PathVariable String userId, @Valid @RequestParam FamilyType familyType) {
当 Postman 送来的时候 familytype=firstname
,但如果发送 familytype=nickname
然后我的转换器返回
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'FamilyType';
nested exception is java.lang.IllegalArgumentException:
No enum constant FamilyType.NICKNAME
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.
1条答案
按热度按时间mfuanj7w1#
在本教程第3节之后,我们可以使用自定义转换器覆盖默认转换
Enum#valueOf
.然后将转换器添加到mvc配置中