RestController的最佳实践是什么?

Cig*_*igi 6 spring spring-boot spring-restcontroller spring-rest

代码约定说控制器中没有逻辑。所有这些都应在服务层中处理。我的问题尤其是关于返回ResponseEntity的问题。

应该在RestController还是在Service层中处理?

我尝试了两种方式。我认为RestController是返回ResponseEntity的合适位置。因为我们在RestController中使用映射。

另一方面,我们知道控制器不应包含任何逻辑。

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
Run Code Online (Sandbox Code Playgroud)

要么

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    return employeeService.findEmployeeById(id);
}
Run Code Online (Sandbox Code Playgroud)

我的另一个担心是用于异常处理的ControllerAdvice。最好使用哪种方式?

感谢您的进步。

dav*_*xxx 8

代码约定说控制器中没有逻辑。

并不是的。代码约定说每一层必须执行自己负责的逻辑。
计算结果,检索请求所请求/需要的数据显然不是其余的控制器工作,而是发送http响应,返回的ResponseEntity是其工作。所以这看起来是正确的方式:

@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
    return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
Run Code Online (Sandbox Code Playgroud)

如果ResponseEntity是由您的服务产生的,则您的服务将与Http层耦合。这是不可取的,并且使其不太可重用为服务。