报错信息
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'com.atguigu.lease.model.enums.LeaseStatus';
Caused by: org.springframework.core.convert.ConversionFailedException:
Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.atguigu.lease.model.enums.LeaseStatus] for value '1'
原因
Spring Context未注册转换器:确保你的StringToBaseEnumConverterFactory被Spring正确扫描并注册到上下文中。
解决方法
在web-app模块的config定义StringToBaseEnumConverterFactory,再注册到WebMvcConfigurer。
//(1)定义StringToBaseEnumConverterFactory
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
return new Converter<String, T>() {
@Override
public T convert(String code) {
T[] enumConstants = targetType.getEnumConstants();//拿到目标类型的全部枚举实例
for (T enumConstant : enumConstants) {
if (enumConstant.getCode().equals(Integer.valueOf(code))) {
return enumConstant;
}
}
throw new IllegalArgumentException("非法的枚举值:" + code);
}
};
}
}
//(2)注册转换器
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private StringToBaseEnumConverterFactory stringToBaseEnumConverterFactory;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(this.stringToBaseEnumConverterFactory);
}
}