自定义枚举转换器正在实例化但未调用

时间:2016-09-13 11:14:56

标签: java spring enums converter

我有以下问题:

团队成员更改了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

我使用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 个答案:

答案 0 :(得分:1)

您是否已将其添加到Spring MVC配置中?

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "..." })
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry formatterRegistry) {
        formatterRegistry.addConverter(getMyConverter());
    }

...