How to call another api from same app in spring boot
Why not are you calling Company service directly(if both controller exists in same application)? It will be more faster than calling company controller.
Your controller will than look like this:
@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
}
}
If still you want to directly call Company Controller, then you can do something like this:
@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
}
}
Sachin
Updated on June 22, 2022Comments
-
Sachin almost 2 years
I have two
RestController
s for user and Company.CompanyController
: fetch from and store company information tocompanies
table using service and repo level.UsersController
: It is used to fetch and store users.Relationship: Each user is associated with company(User hasOne company).
When new
User
get registered, we need to fetch company information by id and associate with user profile.For this, I have one endpoint in
CompanyController
, namedgetCompanyInfo
. I have to call that endpoint to fetch company data while saving user profile.How to call another API from same app in Spring Boot?
-
Afridi almost 7 yearsWhy not are you calling Company service directly(if both controller exists in same application)? It will be more faster than calling company controller.
-
Sachin almost 7 yearsBecause i am doing some calculation as well on Company controller. I dont want to lose or rewrite that
-
Afridi almost 7 yearsController main purpose is to generally validate request parameters and then use respective services for any type of calculation or business logic validation. But still if you want to call controller, then you can use Resttemplate
-
Sachin almost 7 yearsThanks. If i go for first comment moving to service layer. Then how can i utilize EntityToDto and Dtotoentity function present in company controller
-
Afridi almost 7 yearscan you please post your controller code? I don't know how did you implemented your controller's functions like "EntityToDto " etc
-
ScottSummers over 5 yearsYou can autowire the controller and call the methods.