如何在spring boot项目中使用枚举
导读:本文共2460字符,通常情况下阅读需要8分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 1. 在controller的方法中,比如以这个枚举为参数,如下代码:@RequestMapping("/**")publicStringgetRejectReasons(EnumExpenseTypetype){return"";}前台传入的参数如果是type:1, 那它值应该是:小欢喜,实际上呢?Causedby... ...
目录
(为您整理了一些要点),点击可以直达。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项目中使用枚举的详细内容,希望对您有所帮助,信息来源于网络。