spring boot 枚举使用的坑整理
作者:二奎 发布时间:2022-09-17 09:03:15
java 枚举的功能挺多,但是坑更多,使用的时候要注意。如下面这个枚举。
@Getter
@AllArgsConstructor
public enum EnumExpenseType implements BaseEnum {
小欢喜(1),
大欢喜(2);
private final int value;
}
咋一看,没什么问题,但是具体使用过程中,总是会出问题。原因就是这个枚举没有按照从0开始索引,除此之外即使从0开始,中间有断的索引也会有问题。主要出现在以下方面:
1. 在controller的方法中,比如以这个枚举为参数,如下代码:
@RequestMapping("/**")
public String getRejectReasons(EnumExpenseType type) {
return "";
}
前台传入的参数如果是type:1, 那它值应该是:小欢喜,实际上呢?
Caused by: java.lang.IllegalArgumentException: No enum constant com.**.EnumReasonType.1at java.lang.Enum.valueOf(Enum.java:238) ~[?:1.8.0_111]at org.springframework.core.convert.support.StringToEnumConverterFactory$StringToEnum.convert(StringToEnumConverterFactory.java:52) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]at org.springframework.core.convert.support.StringToEnumConverterFactory$StringToEnum.convert(StringToEnumConverterFactory.java:38) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:436) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:191) ~[spring-core-5.1.8.RELEASE.jar:5.1.8.RELEASE]at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:129) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:693) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:124) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]... 81 more
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中转换失败,具体代码如下:
private static class StringToEnum<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType;
public StringToEnum(Class<T> enumType) {
this.enumType = enumType;
}
@Override
public T convert(String source) {
if (source.isEmpty()) {
// It's an empty enum identifier: reset the enum value to null.
return null;
}
return (T) Enum.valueOf(this.enumType, source.trim());
}
}
是Enum.valueOf这里报错,Enum.valueOf的后面的值并不是我们的value,而是name(这里的小欢喜)。
所以,我们不能使用这个spring提供converter,需要自定义一个:StringToEnumConverterFactory
public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
private static final Map<Class, Converter> converterMap = new HashMap<>();
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
Converter<String, T> converter = converterMap.get(targetType);
if(converter == null) {
converter = new StringToEnumConverter<>(targetType);
converterMap.put(targetType, converter);
}
return converter;
}
class StringToEnumConverter<T extends BaseEnum> implements Converter<String, T> {
private Map<String, T> enumMap = new HashMap<>();
StringToEnumConverter(Class<T> enumType) {
T[] enums = enumType.getEnumConstants();
for(T e : enums) {
enumMap.put(String.valueOf(e.getValue()), e);
}
}
@Override
public T convert(String source) {
T t = enumMap.get(source);
if (t == null) {
// 异常可以稍后去捕获
throw new IllegalArgumentException("No element matches " + source);
}
return t;
}
}
}
然后再将这个工厂配置到项目中WebMvcConfigurationSupport:
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(new StringToEnumConverterFactory());
}
意思就是string 转 BaesEnum都走这个converter。
至此这个坑就算解决了。
来源:https://www.cnblogs.com/hankuikui/p/11429689.html


猜你喜欢
- ListView是android中最常用的控件之一。 在实际运用中往往会遇到一次性加载全部数据过多,需要分页加载增加程序运行效率! 本dem
- ClasspathResource路径问题前言在项目中工程以springboot jar形式发布,跟之前容器比少了一个解压目录,这个过程中出
- name和value属性的区别从源码可以得知,name是value的别名,value也是name的别名。两者的作用是一致的,name指定Fe
- 1 引入 pom 包<dependency> <groupId>io.github.res
- 查看JDK1.8 ArrayList的源代码1、默认初始容量为10 /** * Default i
- 在WPF中,当我们要使用MVVM的方式绑定一个普通对象的属性时,界面上往往需要获取到属性变更的通知,class NotifyObject :
- IntelliJ IDEA是很多程序员必备且在业界被公认为最好的Java开发工具,有很多小伙伴在安装完IDEA并且tomcat之后,启动to
- C# 中有三种定时器,System.Windows.Forms 中的定时器和 System.Timers.Timer 的工作方式是完全一样的
- Selenium.WebDriverSelenium WebDriver 是一组开源 API,用于自动测试 Web 应用程序,利用它可以通过
- 本文实例为大家分享了C#实现语音播报功能的具体代码,供大家参考,具体内容如下环境:window10vs2019 16.5.5.netfram
- 起因最近在写CRUD的时候,发现有个分页的VO写的健壮性比较差,一时手痒改了一下,没想到改了之后好几个功能都出现了问题。原VO关键代码如下:
- @RequestBody的作用@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的),所以只能发送
- 一、使用嵌入式关系型SQLite数据库存储数据在Android平台上,集成了一个嵌入式关系型数据库——SQLite,SQLite3支持NUL
- 一.Unsafe类的源码分析JDK的rt.jar包中的Unsafe类提供了硬件级别的原子操作,Unsafe里面的方法都是native方法,通
- windows下使用cmd命令提示符生成java webservice客户端代码,可以使用命令提示符直接生成客户端代码,直接导入到项目中,只
- 这篇文章主要介绍了java内存泄漏与内存溢出关系解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友
- 短网址(Short URL) ,顾名思义就是看起来很短的网址。自从twitter推出短网址服务以后,各大互联网公司都推出了自己的短网址服务。
- Spring Boot 2.x 已经发布了很久,现在 Spring Cloud 也发布了 基于 Spring Boot 2.x 的 Finc
- 通过GPS取得的是一个Location类型的经纬度, 可以转换为两个Double 纬度和经度.纬度: 23.223871812820435纬
- 本文实例讲述了C#保存listbox中数据到文本文件的方法。分享给大家供大家参考。具体实现方法如下:private void SaveLst