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). It makes sense to pack this behaviour away in a base class, perhaps called Controller
.
Firstly, is there a base class like this in Spring already, which I've missed? 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
? 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}")
. Do I write my request-handling methods without the annotations, then wrap and annotate them in each of my 5-6 subclasses, like this?
@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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.