首页 > 解决方案 > 外部函数签名中是否需要 @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()(如果我有很多这样的方法)。

谢谢

标签: javarestjparequestannotations

解决方案


@RequestBody使用in 方法没有任何意义AttributeService。没有框架会处理这个注释。

在我看来, read for GET、 create for POST、 update forPUT和 delete forDELETE分别是 HTTP 方法的好方法名称。正如您所说,任何名称都可以使用。


推荐阅读