代码约定表明控制器中没有逻辑。一切都应该在服务层处理。我的问题特别是关于返回 ResponseEntity。
应该在RestController中处理还是在Service层中处理?
我两种方法都尝试过。我认为 RestController 是返回 ResponseEntity 的合适地方。因为我们在 RestController 中使用映射。
另一方面,我们知道控制器不应该包含任何逻辑。
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
or
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return employeeService.findEmployeeById(id);
}
针对异常处理的 ControllerAdvice 是我的另一个关注点。使用哪种方式最好?
感谢您的提前。
代码约定表明控制器中没有逻辑。
并不真地。代码约定规定每一层都必须执行其负责的逻辑。
计算结果、检索请求所请求/需要的数据显然不是其余控制器的工作,而是发送 http 响应,返回什么ResponseEntity
做是它的工作。所以这看起来是正确的方法:
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
If the ResponseEntity
由您的服务生成,您的服务将与 Http 层耦合。不可取,并且会降低其作为服务的可重用性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)