繁体   English   中英

如何为每个 controller 设置不同的基础 url

[英]How to set a different base url for each controller

将行spring.data.rest.basePath=/api添加到我的application.properties文件中,因此每个端点都以/api开头。

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

如果我在这两个 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);
}

我希望第一个是/api/customer/getById/{id}和第二个/api/provider/getById/{id}

有什么方法可以实现这一点而无需在每个注释上手动输入?

谢谢你。

是的,您可以提取路径的公共部分并将其放入 controller 上的@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);
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM