简体   繁体   English

Spring:我可以将我的请求映射抽象到基础 class 吗?

[英]Spring: Can I abstract my request mappings away to a base class?

My Spring Boot application has a bunch of REST controller classes, all of which perform more or less the same standard CRUD operations on their respective models, just with different endpoint names (one is /user , one is /group , etc).我的 Spring 引导应用程序有一堆 REST controller 类,所有这些类都在各自的模型上执行或多或少相同的标准 CRUD 操作(一个是/user /group ,是等) It makes sense to pack this behaviour away in a base class, perhaps called Controller .将此行为打包到基础 class 中是有意义的,可能称为Controller

Firstly, is there a base class like this in Spring already, which I've missed?首先,在 Spring 中是否有像这样的基础 class ,我错过了? It seems like handy behaviour that lots of people would need, so I'm surprised I can't find it.这似乎是很多人需要的方便行为,所以我很惊讶我找不到它。

If not, and I need to write it myself, my problem is: what do I do with the request mapping annotations, like @GetMapping and @PostMapping ?如果没有,我需要自己编写,我的问题是:我该如何处理请求映射注释,例如@GetMapping@PostMapping Their value argument has to be constant, so I can't just use the annotations in the superclass and interpolate each endpoint name into them, as in @GetMapping("/" + endpointName + "/{id}") .它们的value参数必须是常量,所以我不能只使用超类中的注释并将每个端点名称插入其中,如@GetMapping("/" + endpointName + "/{id}") Do I write my request-handling methods without the annotations, then wrap and annotate them in each of my 5-6 subclasses, like this?我是否在没有注释的情况下编写我的请求处理方法,然后在我的 5-6 个子类中的每个子类中包装和注释它们,就像这样?

@RestController
public abstract class Controller<T> {

    public ResponseEntity<T> create(T obj) {
        // Creation behaviour
    }

    // Same for retrieve, update, etc

}

...

public class UserController extends Controller<User> {

    @Override
    @PostMapping("/user")
    public ResponseEntity<User> create(@RequestBody User user) {
        return super.create(user);
    }

    // Repeat for other operations

}

// and repeat for all the other subclasses

It seems a little redundant;似乎有点多余; I'd love it if there was a cleaner way.如果有更清洁的方法,我会喜欢的。

You can create a generic abstract controller for your CRUD mappings, like:您可以为您的 CRUD 映射创建通用抽象 controller,例如:

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
}

Then your controller will extend the abstract controller.然后您的 controller 将扩展抽象 controller。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM