将行spring.data.rest.basePath=/api
添加到我的application.properties
文件中,这样每个端点都以/api
开始。
除此之外,我希望每个控制器";"增量";此url。例如,假设我有两个不同的控制器,CustomerController
和ProviderController
。
如果我在这两个函数中都定义:
//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
中:
@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);
}
}
您可以在控制器上使用@RequestMapping("/example/url")
注释。
@Controller
@RequestMapping("/url")
class HomeController() {}