如何在 spring 启动时从同一个应用调用另一个 api

How to call another api from same app in spring boot

我有两个 RestController 用于用户和公司。

当新 User 注册时,我们需要通过 id 获取公司信息并与用户个人资料关联。

为此,我在 CompanyController 中有一个端点,名为 getCompanyInfo。我必须在保存用户配置文件的同时调用该端点来获取公司数据。

如何在 Spring 启动时从同一个应用调用另一个 API?

你为什么不直接调用公司服务(如果两个控制器都存在于同一个应用程序中)?比打电话给公司管家要快

您的控制器将如下所示:

@RestController
public class UsersController {
    @Autowired
    private CompanyService companySerivce;

    @RequestMapping("/register")
    public ResponseEntity<User> registerUser(){
        //Do whatever you want
        CompanyInfo companyInfo = companyService.getCompanyInfo();
       //Do whatever you want
    }
}

如果你还想直接调用Company Controller,那么你可以这样做:

@RestController
public class UsersController {
    @Autowired
    private RestTemplate template;

    @RequestMapping("/register")
    public ResponseEntity<User> registerUser(){
        ResponseEntity<CompanyInfo> companyInfoResponse = template.getForObject("Url for getCompanyInfo() method", CompanyInfo.class);
        CompanyInfo companyInfo = companyInfoResponse.getBody();
        //Do whatever you want
    }
}