SpringMVC 接收枚举参数 自动转换

 
public class EnumConverter implements Converter {
   private Class enumType;

   public EnumConverter(Class enumType) {
      this.enumType = enumType;
   }

   @Override
   public T convert(String source) {
      if (source.length() == 0) {
         return null;
      }
      return (T) enumType.getEnumConstants()[Integer.parseInt(source)];
   }
}



@Component
public class EnumConverterFactory implements ConverterFactory {
   @Override
   public  Converter getConverter(Class targetType) {
      return new EnumConverter(targetType);
   }
}
​​​​​​​@Configuration
public class MvcConfigure implements WebMvcConfigurer {
   @Autowired
   private EnumConverterFactory enumConverterFactory;

   @Override
   public void addFormatters(FormatterRegistry registry) {
      registry.addConverterFactory(enumConverterFactory);
   }

}

你可能感兴趣的:(Java)