自定义Converter
首先创建一个converter
类并继承converter
接口,并重写其中的converter方法。例如:
@Component
public class StringToItemTypeConverter implements Converter<String, ItemType> {
@Override
public ItemType convert(String code) {
for (ItemType value : ItemType.values()) {
if (value.getCode().equals(Integer.valueOf(code))) {
return value;
}
}
throw new IllegalArgumentException("code非法");
}
}
然后创建WebMvcConfiguration
类并继承WebMvcConfigurer
接口,将创建的converter类注册到SpringMVC
中。例如:
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private StringToItemTypeConverter stringToItemTypeConverter;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(this.stringToItemTypeConverter);
}
}
自定义ConverterFactory
当我们有很多的类型都需要考虑类型转换问题时,我们可以尝试自定义一个ConverterFactory
,这个接口可以将同一个转换逻辑应用到一个接口的所有实现类,它所转换的目标类型是我们所需要转换的目标类型的父类。
首先创建一个converterFactory
类并继承converterFactory
接口,并重写其中的converterFactory
方法。例如:
@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 source) {
for (T enumConstant : targetType.getEnumConstants()) {
if (enumConstant.getCode().equals(Integer.valueOf(source))) {
return enumConstant;
}
}
throw new IllegalArgumentException("非法的枚举值:" + source);
}
};
}
}
然后创建WebMvcConfiguration
类并继承WebMvcConfigurer
接口,将创建的converterFactory
类注册到SpringMVC
中。例如:
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private StringToBaseEnumConverterFactory stringToBaseEnumConverterFactory;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(this.stringToBaseEnumConverterFactory);
}
}