如何在spring boot项目中使用枚举(springboot,枚举,编程语言)

时间:2024-05-01 09:09:57 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

    %E5%A6%82%E4%BD%95%E5%9C%A8spring+boot%E9%A1%B9%E7%9B%AE%E4%B8%AD%E4%BD%BF%E7%94%A8%E6%9E%9A%E4%B8%BE

1. 在controller的方法中,比如以这个枚举为参数,如下代码:

前台传入的参数如果是type:1, 那它值应该是:小欢喜,实际上呢?

Failed to convert value of type 'java.lang.String' to required type 'com.**.EnumExpenseType';
nested exception is org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [com.**.EnumExpenseType] for value '1';
nested exception is java.lang.IllegalArgumentException: No enum constant com.***.EnumExpenseType.1

实际上它却报了个错。转换失败了。

查看报错信息,可以定位到是spring框架中StringToEnumConverterFactory中转换失败,具体代码如下:

是Enum.valueOf这里报错,Enum.valueOf的后面的值并不是我们的value,而是name(这里的小欢喜)。

所以,我们不能使用这个spring提供converter,需要自定义一个:StringToEnumConverterFactory

然后再将这个工厂配置到项目中WebMvcConfigurationSupport:

本文:如何在spring boot项目中使用枚举的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:springboot文件打包成jar或war的方法下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18