Search code examples
springspring-restcontroller

Spring - Is it possible to inherit a RestController with its RequestMapping


Let's say I have a parent entity Vehicule and some children entities Car, Bike, Ship, Plane. I have one generic repository which handles all entities:

public interface VehiculeRepository<T extends Vehicule> extends JpaRepository<T, Long> {
    // ...
}

I also have a generic VehiculeService<T extends Vehicule> class that take care of all the BREAD functions and some children services like:

public class CarService extends VehiculeService<Car> {
    // ...
}

NOTE: BREAD stands for Browse, Read, Edit, Add & Delete, aka CRUD

I'm wondering if I can create a generic RestController with its RequestMapping and inherit it for the child entities. something like

@RestController
@RequestMapping("/api/vehicules")
@RequiredArgsConstructor
public class VehiculeController<S extends VehiculeService> {

    private final S service;

    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<VehiculeResponse> browse() {
        return service.browse();
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void create(@Valid @ModelAttribute VehiculeRequest request) {
        service.create(request);
    }

    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public VehiculeResponse read(@PathVariable Long id) {
        return service.read(id);
    }

    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void edit(@Valid @ModelAttribute VehiculeRequest request, @PathVariable Long id) {
        service.edit(request, id);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable Long id) {
        service.delete(id);
    }
}

Is it possible to create, let's say a CarController with the following code:

@RestController
@RequestMapping("/api/cars")
public class CarController extends VehiculeController<CarService> {
    public CarController(CarService service) {
        super(service);
    }
}

And have all the methods stated in parent correctly mapped & functionning without having to redefine them:

Function Name Mapped Request Method URL
browse GET http://HOST/api/cars
create POST http://HOST/api/cars
read GET http://HOST/api/cars/{id}
edit PUT http://HOST/api/cars/{id}
delete DELETE http://HOST/api/cars/{id}

Solution

  • Short answer, YES I tried it out & apparently the RequestMapping on the methods in parent class are applied correctly in child class, only the root RequestMapping on the controller itself has been affected. The requested behaviour is well achieved!

    NOTE: I marked the parent class as abstract