春季:我可以将我的请求映射抽象到基类吗?

时间:2020-05-09 17:57:17

标签: java spring

我的Spring Boot应用程序具有一堆REST控制器类,所有这些类在各自的模型上执行或多或少相同的标准CRUD操作,只是端点名称不同(一个是/user,一个是{{ 1}}等)。将这种行为打包在一个可能称为/group的基类中是很有意义的。

首先, Spring已经有这样的基类了,我错过了吗?似乎很多人都需要这种方便的行为,所以我很惊讶我不能找到它。

如果没有,我需要自己写,我的问题是:我如何处理请求映射注释,例如Controller@GetMapping?它们的@PostMapping参数必须是常量,因此,我不能像value那样仅使用超类中的注释并将每个端点名称插入其中。我是否要在没有注释的情况下编写请求处理方法 ,然后像这样在我的5-6个子类中包装它们并对其进行注释?

@GetMapping("/" + endpointName + "/{id}")

似乎有点多余;如果有更清洁的方法,我会喜欢的。

1 个答案:

答案 0 :(得分:1)

您可以为CRUD映射创建通用的抽象控制器,例如:

public abstract class AbstractGenericController<E extends yourGenericEntity> {
private static final Logger LOG = LoggerFactory.getLogger(AbstractGenericController.class);
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity<GenericResult<T>> create(@RequestBody String input) {
// your process
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ResponseEntity<GenericResult<T>> update(@RequestBody String input) {
// your process
}

然后您的控制器将扩展抽象控制器。