如何为每个控制器设置不同的基数url

How to set a different base url for each controller

spring.data.rest.basePath=/api 行添加到我的 application.properties 文件使得每个端点都以 /api.

开头

最重要的是,我希望每个控制器“增加”这个 url。例如,假设我有 2 个不同的控制器,CustomerControllerProviderController

如果我在这两个函数中定义:

//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);
}

我想要第一个 /api/customer/getById/{id} 第二个 /api/provider/getById/{id}.

有什么方法可以做到这一点而不必在每个注释上手动键入它吗?

谢谢。

您可以在控制器上使用 @RequestMapping("/example/url") 注释。

@Controller
@RequestMapping("/url")
class HomeController() {}

是的,您可以提取路径的公共部分并将其放入控制器上的 @RequestMapping 中:

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

    // ...

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

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

    // ...

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