springboot接收enum
时间: 2025-02-20 09:36:43 浏览: 31
### 接收枚举类型参数
在Spring Boot中,为了使应用能够接收并处理枚举类型的参数,通常会采用`@InitBinder`来注册自定义编辑器,该方法允许开发者指定如何将HTTP请求中的字符串形式的数据转换成相应的Java对象实例,在这里即是指定如何把来自客户端的输入转化为对应的枚举值[^1]。
下面是一个具体的例子展示怎样创建一个RESTful API端点以接受路径变量形式传入的问题类型(假设为QuestionType),并将之映射到服务器端的一个特定操作上:
#### 定义枚举类 `QuestionType`
```java
public enum QuestionType {
SINGLE_CHOICE,
MULTIPLE_CHOICES,
TRUE_FALSE;
}
```
#### 创建控制器 `QuestionController`
```java
@Controller
@RequestMapping("/questions")
public class QuestionController {
@GetMapping("/{type}")
public ResponseEntity<String> getResponseByQuestionType(@PathVariable("type") QuestionType type){
switch (type){
case SINGLE_CHOICE -> {return ResponseEntity.ok("Single choice question");}
case MULTIPLE_CHOICES -> {return ResponseEntity.ok("Multiple choices question");}
case TRUE_FALSE -> {return ResponseEntity.ok("True or false question");}
default -> throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Invalid question type");
}
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(QuestionType.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
try{
setValue(QuestionType.valueOf(text.toUpperCase()));
}catch(IllegalArgumentException e){
logger.error("Failed to parse value [" + text + "] as an instance of QuestionType.");
throw new IllegalArgumentException("Parameter must be one of the following values: "
+"SINGLE_CHOICE, MULTIPLE_CHOICES, TRUE_FALSE",e);
}
}
});
}
}
```
上述代码片段实现了当接收到诸如`/questions/SINGLE_CHOICE`这样的URL访问时,可以根据路径中的枚举名称匹配相应的行为逻辑,并返回恰当的信息给调用者。同时利用了`@InitBinder`注解下的`initBinder()`函数配置了一个针对`QuestionType`类型的属性编辑器,确保即使是从表单提交或者是查询串方式传递过来的小写字母也能被正确解析为大写的枚举常量名。
此外,通过合理运用枚举参数还可以增强程序的可读性和易于维护性,使得业务逻辑更加清晰明了[^2]。
阅读全文
相关推荐


















