如何在requestparm中将多个值转换为enum?

x33g5p2x  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(459)

我有下面的枚举声明

  1. public enum FamilyType {
  2. FIRSTNAME("firstname"),
  3. LASTNAME("lastname");
  4. private final String type;
  5. FamilyType(String type) {
  6. this.type = type;
  7. }
  8. public static FamilyType fromString(String type) {
  9. for (FamilyType t : FamilyType.values()) {
  10. if (t.type.equals(type)) {
  11. return t;
  12. }
  13. }
  14. return converter(type);
  15. }
  16. @Deprecated
  17. private static FamilyType converter(String value) {
  18. if ("NICKNAME".equalsIgnoreCase(value)) {
  19. return FIRSTNAME;
  20. }
  21. if ("SURENAME".equalsIgnoreCase(value)) {
  22. return LASTNAME;
  23. }
  24. throw new InvalidFileNameException("my-enum", value);
  25. }
  26. }

我有一个控制器端点,其中delete请求保存 FamilyType 作为 Requestparam 如下所示

  1. public String deleteFamilyType(@PathVariable String userId, @Valid @RequestParam FamilyType familyType) {

当 Postman 送来的时候 familytype=firstname ,但如果发送 familytype=nickname 然后我的转换器返回

  1. org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
  2. Failed to convert value of type 'java.lang.String' to required type 'FamilyType';
  3. nested exception is java.lang.IllegalArgumentException:
  4. No enum constant FamilyType.NICKNAME
  5. at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
  6. at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
  7. at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
  8. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
  9. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.
mfuanj7w

mfuanj7w1#

在本教程第3节之后,我们可以使用自定义转换器覆盖默认转换 Enum#valueOf .

  1. public class StringToFamilyTypeConverter implements Converter<String, FamilyType> {
  2. @Override
  3. public FamilyType convert(String source) {
  4. if ("NICKNAME".equalsIgnoreCase(source)) {
  5. return FamilyType.FIRSTNAME;
  6. }
  7. if ("SURENAME".equalsIgnoreCase(source)) {
  8. return FamilyType.LASTNAME;
  9. }
  10. return FamilyType.valueOf(source.toUpperCase());
  11. }
  12. }

然后将转换器添加到mvc配置中

  1. @Configuration
  2. public class AppConfig implements WebMvcConfigurer {
  3. // ...
  4. @Override
  5. public void addFormatters(FormatterRegistry registry) {
  6. registry.addConverter(new StringToFamilyTypeConverter());
  7. }
  8. // ...
  9. }
展开查看全部

相关问题