spring - java - 如何在java spring中获取自定义对象?
问题描述
我正在为我的服务器使用 java spring。
我的问题是如何通过控制器获取自定义对象。
我的意思的例子:
我知道我可以通过执行两个功能来做到这一点:
@RequestMapping(
path = arrayOf("getObject", "getObject/"),
method = arrayOf(RequestMethod.GET))
open fun getRecord1(@RequestBody data: CustomObjectOption1): ResponseEntity<*> {
return ResponseEntity<Any>(data.name,HttpStatus.OK)
}
@RequestMapping(
path = arrayOf("getObject", "getObject/"),
method = arrayOf(RequestMethod.GET))
open fun getRecord2(@RequestBody data: CustomObjectOption2): ResponseEntity<*> {
return ResponseEntity<Any>(data.number,HttpStatus.OK)
}
但我只想通过一个端点来做到这一点:
@RequestMapping(
path = arrayOf("getObject", "getObject/"),
method = arrayOf(RequestMethod.GET))
open fun getRecord(@RequestBody data: CustomObjectOption): ResponseEntity<*> {
if(data instance option1)
return ResponseEntity<Any>(data.name,HttpStatus.OK)
否则返回 ResponseEntity(data.number,HttpStatus.OK) 否则 }
这样对象可以是这样的:
选项1:
public class CustomObject {
private String name;
private Long id;
}
或选项 2:
public class CustomObject {
private List<Integer> number;
private List<Long> count;
}
在java spring中可以做到这一点吗?
我想的唯一解决方案是使用继承,但我想知道是否有不同的方式......
感谢您的帮助
解决方案
正如您所写,您可以这样做:
@RequestMapping(...)
public void method(@RequestBody YourCustomClass body)
YourCustomClass
可以是选项 1 或选项 2。
就这样 :)
推荐阅读
- flutter - 错误提示在 DART 的初始化程序中只能访问静态成员
- loops - 如何创建最终停止的循环
- android - 我们如何将值/参数从 android APK 传递到 React JS 浏览器。?
- spring-boot - Spring Cloud Gateway Fallback on 404 Status Code from route
- javascript - OpenLayers 5 绘制交互 - Draw.js:338 中的“n 不是构造函数”
- python - 如何使用基于类的视图继承来覆盖父类?
- javascript - 如何将此静态函数转换为允许参数的函数?
- javascript - 通用传感器 API 在本地主机上不起作用
- sql - 在多列上连接 2 个表并根据每个连接提取值
- android - 如何在我的应用程序中添加两个数据库?这是一个好习惯吗?