gpt4 book ai didi

spring - RestController的最佳实践是什么?

转载 作者:行者123 更新时间:2023-12-04 13:36:09 25 4
gpt4 key购买 nike

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

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

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

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

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

或者
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return employeeService.findEmployeeById(id);
}

我的另一个顾虑是用于异常处理的ControllerAdvice。最好使用哪种方法?

感谢您的进步。

最佳答案

Code convention says no logic in the controllers.



并不真地。代码约定说,每一层都必须执行自己负责的逻辑。
计算结果,检索请求所请求/需要的数据显然不是其余的 Controller 工作,而是发送http响应,返回 ResponseEntity所做的就是它的工作。因此,这看起来是正确的方式:
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}

如果 ResponseEntity由您的服务生成,则您的服务将与Http层耦合。这是不可取的,因此使其作为服务的可重用性降低了。

关于spring - RestController的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57284058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com