我有以下string到enum转换器工厂:
public final class StringToEnumConverterFactory implements ConverterFactory<String, Enum<?>> {
public <T extends Enum<?>> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToEnumConverter(targetType);
}
@RequiredArgsConstructor
private static final class StringToEnumConverter<T extends Enum<T>> implements Converter<String, T> {
private final Class<T> enumType;
public T convert(String source) {
try {
return Enum.valueOf(this.enumType, source.toUpperCase().trim());
} catch (IllegalArgumentException e) {
throw new RuntimeException("Argument invalid " + source);
}
}
}
}
我已经实现了以下控制器:
public interface GetGraphsController {
@GetMapping(value = "/graphs", produces = MediaType.APPLICATION_JSON_VALUE)
Graphs getGraphs(@RequestParam GraphType graphType);
}
GraphType对应于以下内容enum:
public enum GraphType {
A,
B;
}
由于graphType是必需的,我希望 Spring 在请求时抛出异常/graphs?graphType=(注意 nographType包括在内)。但是,允许传递 no graphType,并且不会引发错误。
我也尝试将以下条件添加到convert,但结果是相同的:
if (source.isBlank()) {
throw new RuntimeException("Argument invalid " + source);
}