How to set a different base url for each controller

Adding the line spring.data.rest.basePath=/api to my application.properties file makes it so every endpoint starts with /api.

On top of that, I want each controller to “increment” this url. For example, assume I have 2 different controllers, CustomerController and ProviderController.

If I define in both this function:

//CustomerController
@Autowired
private CustomerService service;

@GetMapping("/getById/{id}")
public Customer findCustomerById(@PathVariable int id) {
    return service.getCustomerById(id);
}

//ProviderController
@Autowired
private ProviderService service;

@GetMapping("/getById/{id}")
public Provider findProviderById(@PathVariable int id) {
    return service.getProviderById(id);
}

I want the first one to be /api/customer/getById/{id} and the second /api/provider/getById/{id}.

Is there any way to achieve this without manually having to type it on each annotation?

Thank you.

Answer

Yes, you can extract the common part of the path and put it into @RequestMapping on your controller:

@RestController
@RequestMapping("/api/customer")
public class CustomerController {

    // ...

    @GetMapping("/getById/{id}")
    public Customer findCustomerById(@PathVariable int id) {
        return service.getCustomerById(id);
    }
}

and

@RestController
@RequestMapping("/api/provider")
public class ProviderController {

    // ...

    @GetMapping("/getById/{id}")
    public Provider findProviderById(@PathVariable int id) {
        return service.getProviderById(id);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *