Spring Boot 2.5.5实现请求参数枚举大小写不敏感并设默认值
解决Spring Boot 2.5.5中枚举请求参数大小写不敏感及默认值问题
你之前尝试的Jackson相关配置(比如ACCEPT_CASE_INSENSITIVE_ENUMS)之所以无效,是因为**@RequestParam的参数解析由Spring MVC的ConversionService负责,而非Jackson**——Jackson仅处理@RequestBody这类JSON请求体的序列化/反序列化,对URL中的请求参数不生效。
下面提供两种可行的解决方案:
方案一:自定义全局Converter(推荐)
通过实现Spring的Converter接口,统一处理枚举参数的大小写转换和默认值逻辑,全局生效。
1. 创建枚举转换类
import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; @Component public class EmployeeModeConverter implements Converter<String, EmployeeMode> { @Override public EmployeeMode convert(String source) { // 处理空参数或空白字符串 if (source == null || source.trim().isEmpty()) { return EmployeeMode.ALL; } try { // 统一转大写后匹配枚举值 return EmployeeMode.valueOf(source.trim().toUpperCase()); } catch (IllegalArgumentException e) { // 参数无效时返回默认值(也可根据需求抛自定义异常) return EmployeeMode.ALL; } } }
2. 注册Converter到Spring MVC(可选,若@Component未自动生效)
如果自定义Converter未被Spring自动识别,可通过配置类手动注册:
import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new EmployeeModeConverter()); } }
3. 保持原Controller代码不变
此时@RequestParam会自动使用自定义Converter解析参数,空值或无效值都会被转为ALL:
@GetMapping(value = "/employees") public List<Employee> getEmployees( @RequestParam(value = "mode", required = false) final EmployeeMode mode) { // 直接使用mode即可 // calling service from here }
方案二:枚举内部静态方法处理(快速实现)
如果不想配置全局Converter,可在枚举类中添加静态方法,手动处理参数转换。
1. 扩展枚举类
public enum EmployeeMode { REGULAR, ALL, TEMPROARY; public static EmployeeMode parse(String value) { if (value == null || value.trim().isEmpty()) { return ALL; } try { return EmployeeMode.valueOf(value.trim().toUpperCase()); } catch (IllegalArgumentException e) { return ALL; } } }
2. 修改Controller方法
将请求参数改为String类型,调用枚举的静态方法转换:
@GetMapping(value = "/employees") public List<Employee> getEmployees( @RequestParam(value = "mode", required = false) final String modeStr) { EmployeeMode mode = EmployeeMode.parse(modeStr); // calling service from here }
方案对比
- 方案一:全局生效,所有使用
EmployeeMode作为@RequestParam的接口都会自动处理,代码更优雅,适合多接口场景。 - 方案二:无需额外配置,代码更直接,适合单个接口的快速实现。
内容的提问来源于stack exchange,提问作者Remo
相关产品推荐
相关产品推荐

