代码约定说 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。最好使用哪种方法?
感谢您的进步。
最佳答案
并不真地。代码约定说,每一层都必须执行自己负责的逻辑。
计算结果,检索请求所请求/需要的数据显然不是其余的 Controller 工作,而是发送http响应,返回ResponseEntity
所做的就是它的工作。因此,这看起来是正确的方式:
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
如果
ResponseEntity
由您的服务生成,则您的服务将与Http层耦合。这是不可取的,因此使其作为服务的可重用性降低了。