0

我正在使用spring 4REST。

我有一个基础class和许多其他class扩展相同。例如,员工是基础class,其他类 hr、工程师、培训师等扩展员工。

我必须创建REST API以创建不同类型的员工。这interface是一个POST接受所有类型的员工。我不能interface为每个子类型创建不同的。从基础上,我知道什么是子类型。

@RequestMapping(value= "/test/{employeeType}", method = RequestMethod.POST)
public void createEmp(@RequestBody Employee employee){

    //If type is HR, I want to cast to HR type
    //Is there any way we can take generic object in spring rest and then manage internally ?

}
4

1 回答 1

0

也许试试这个?

@RequestMapping(value= "/test/{employeeType}", method = RequestMethod.POST)
public void createEmp(@PathVariable String employeeType, @RequestBody EmployeeDTO employeeDTO){
   transform(employeeType,employeeDTO);
}

这里 EmployeeDTO 将包含所有可能的参数,因此它可以构造任何子类,然后基于您刚刚转换为域对象(Employee)的employeeType?

根据要求编辑2

这是示例代码:

public class Employee {

private String name;

}

public class Hr extends Employee {

private String department;

}

public class Hr extends Employee {

private String department;

}

那么 DTO 类应该如下所示:

public class EmployeeDTO {

private String name;
private String course;
private String department;

}

然后,当您知道您的类型时,您可以使用 DTO 中的所有必要值转换为您想要的任何类型

编辑:现在当我考虑它时,这也可能是一个选择,但我需要看看你的课程。

@RequestMapping(value= "/test/employee", method = RequestMethod.POST)
public void createEmp(@RequestBody Employee employee){

@RequestMapping(value= "/test/hr", method = RequestMethod.POST)
public void createHr(@RequestBody Hr hr){
于 2015-07-25T09:56:47.517 回答