本文介绍了RestController 的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码约定表示控制器中没有逻辑.一切都应该在服务层处理.我的问题特别是关于返回 ResponseEntity.

Code convention says no logic in the controllers. All should be handled in the service layer. My question is especially about returning ResponseEntity.

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

Should it be handled in RestController or in Service layer?

两种方法我都试过了.我认为 RestController 是返回 ResponseEntity 的合适位置.因为我们在 RestController 中使用映射.

I tried both ways. I think RestController is the suitable place to return ResponseEntity. Because we are using mappings in the RestController.

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

On the other hand, we know the controllers should not include any logic.

@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 是我的另一个关注点.哪种方式最好用?

ControllerAdvice for exception handling is my another concern. Which way is the best to use?

感谢您的提前.

推荐答案

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

Not really. Code convention says each layer has to perform itself logic which it is responsible of.
Computing the result, retrieving data requested/needed by the request is clearly not the rest controller job but sending an http response, what returning ResponseEntity does is its job. So this looks the correct way :

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

如果 ResponseEntity 是由您的服务生成的,您的服务将与 Http 层耦合.不可取并使其作为服务的可重用性降低.

If the ResponseEntity was produced by your service, your service would be coupled with the Http layer. Not desirable and make it less reusable as a service.

这篇关于RestController 的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 23:39