0
我有以下問題:自定義枚舉器被實例化,但不叫
團隊成員改變了SENSA/Ext JS的前端,併發送帶有空格,而不是下劃線一個parmeter。我不知道該項目的前端代碼爲好,這也是造成以下錯誤:使用招
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
我改變了請求的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");
}
}
}
}
首先,將自定義轉換器添加到現有轉換器而不是將其替換爲您的自定義轉換器可能是個好主意。你怎麼知道這不叫?這種配置是否以某種方式「聲明」(即春天是否知道它)?你確定你的轉換器用'_'替換空間嗎?難道你不能要求前端人員/ gal來解決他/她的混亂問題嗎? –
也看到這個問題:http://stackoverflow.com/questions/11273443/how-to-configure-spring-conversionservice-with-java-config(可能是你的問題) –
@RC我把斷點'內轉換'方法。 org.springframework.core.convert.support.StringToEnum.convert方法被調用,這是默認的彈簧...但不是我自己的,以引入黑客。我跟後端人談過,結果我需要重建前端的js代碼。然而,這仍然使我煩惱...爲什麼不是我自己的轉換方法被稱爲具體的枚舉類型? –