首页 > 解决方案 > 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中可以做到这一点吗?

我想的唯一解决方案是使用继承,但我想知道是否有不同的方式......

感谢您的帮助

标签: springkotlincontroller

解决方案


正如您所写,您可以这样做:

@RequestMapping(...)
public void method(@RequestBody YourCustomClass body)

YourCustomClass可以是选项 1 或选项 2。

就这样 :)


推荐阅读