java - 外部函数签名中是否需要 @PathVariable 或 @RequestBody?
问题描述
我有一个关于约定的问题。一切正常(感谢上帝),但我不确定在我的 AttributeService 类方法签名中是否需要注释(@PathVariable 和 @RequestBody):
@Autowired
private AttributeRepository attributeRepository;
public Attribute create(@RequestBody Attribute attribute) {
return attributeRepository.save(attribute);
}
它可能与它们一起使用或不使用它们,但它们在我的@RestController 控制器之外有任何用途吗?控制器方法看起来像这样(这里我当然需要这些注解):
@PostMapping(consumes = "application/json")
public Attribute create(
@RequestBody Attribute attribute
) {
return attributeService.create(attribute);
}
我的意思是,如果我浏览我的服务类并看到黄色注释,这会让我感到困惑,我误以为我在 Controller 类中:)
另一个问题,如果它们具有相同的名称“create”可以吗?控制器方法的名称实际上并不重要,因为它是自动调用的,但我问的是约定。我发现使它们具有相同的名称很容易,所以我很快就知道来自控制器的 create() 正在服务中调用 create()(如果我有很多这样的方法)。
谢谢
解决方案
@RequestBody
使用in 方法没有任何意义AttributeService
。没有框架会处理这个注释。
在我看来, read for GET
、 create for POST
、 update forPUT
和 delete forDELETE
分别是 HTTP 方法的好方法名称。正如您所说,任何名称都可以使用。
推荐阅读
- javascript - Android - Socket.io 未连接
- laravel - 如何配置 Laravel 以使用 PhpRedis?
- sql - 仅从另一个联接表中选择第一行
- opc-ua - 如何与 Openmodelica 嵌入式 opc-ua 服务器交互
- node.js - 如何在角度 10 中调用 api
- ag-grid - ag-grid 将 cellRendererParams 设置为行数据中的值
- r - 根据计算有条件地重新标记行
- asp.net - 通过 Excel/Word 中的超链接打开的选项卡无法识别会话 cookie
- ios - 在 Swift 中调用的第一个函数?
- python-3.x - 无法附加到数组元素