I have a REST Controller in my Spring Boot application as follows:
@RestController public class StudentController { @Autowired private StudentDao studentDao; @GetMapping("/students") public List<Student> getAllStudents(){ return studentDao.getStudent(); } @GetMapping("/students") public Student getStudent(@RequestParam(name="id") int id){ return studentDao.getStudent(id); } }
Upon trying to start the application, I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'studentController' method com.example.rest.webservice.restwebservice.StudentController#getStudent(int) to {GET [/students]}: There is already 'studentController' bean met
Upon changing the endpoints(in the getmapping part), this works perfectly. I fail to understand that since it does not recognise one with query param and one without as 2 separate points, then what is the possible fix for this? I am still a beginner so it would be great if someone could help.
hod
Advertisement
Answer
Usually in REST when you want a list of all students you make it
@GetMapping("/students")
as you have done.
If you need just one one specific student by id the id is a path variable like:
@GetMapping("/students/{id}") public Student getStudent(@PathVariable(name="id") int id)
So not exactly overloading.
Check also this