正在实例化java自定义枚举转换器,但未调用
我有以下问题:
一名团队成员更改了sensa/ext js前端,正在发送带有空格而不是下划线的参数。我也不知道项目的前端代码,这导致了以下错误:
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.RequestParam org.company.project.persistence.enums.DocumentTypeEnum for value 'EXPERT OPINION'; nested exception is java.lang.IllegalArgumentException: No enum constant org.company.project.persistence.enums.DocumentTypeEnum.EXPERT OPINION
我使用fiddler更改了请求的get参数,发现问题是发送的是EXPERT OPINION
而不是EXPERT_OPINION
最初,我添加了一个filter
并尝试更改get参数值,但我必须添加一个包装器,因为您无法直接修改http请求。但是,底层转换器似乎直接从原始http请求获取parameter
值,因此失败
然后我决定试着做一个定制的转换器。我创建了以下类,该类在我运行项目时实例化,但从未调用它来执行特定转换:
@Configuration
public class EnumCustomConversionConfiguration {
@Bean
public ConversionService getConversionService() {
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(getConverters());
bean.afterPropertiesSet();
ConversionService object = bean.getObject();
return object;
}
private Set<Converter> getConverters() {
Set<Converter> converters = new HashSet<Converter>();
converters.add(new StringToEnumConverter(DocumentTypeEnum.class));
return converters;
}
@SuppressWarnings("rawtypes")
private final class StringToEnumConverter<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType;
public StringToEnumConverter(Class<T> enumType) {
this.enumType = enumType;
}
@SuppressWarnings("unchecked")
public T convert(String source) {
checkArg(source);
return (T) Enum.valueOf(enumType, source.trim());
}
private void checkArg(String source) {
// In the spec, null input is not allowed
if (source == null) {
throw new IllegalArgumentException("null source is in allowed");
}
}
}
}
# 1 楼答案
你把它添加到Spring MVC配置中了吗