What is meant by @GetMapping annotation?
@GetMapping annotation in Spring is a powerful for building RESTful web services. It maps HTTP GET requests to a specific handler method in Spring controllers. With the help of @GetMapping annotation we can easily define endpoints of RESTful API and handle various HTTP requests. @GetMapping annotation is used for mapping HTTP GET requests onto specific handler methods. It is composed annotation that acts as a shortcut for @RequestMapping(method=RequestMethod.GET).
Examples of @GetMapping annotation
Example 1:
Java
@GetMapping ( "/students" ) public List<Student> getAllStudents() { return studentRepository.findAll(); } |
In the above example getAllStudents method is annotated with @GetMapping annotation. This means that getAllStudents method will be called when an HTTP Get request is received at the /students URL.
Example 2:
Java
@GetMapping ( "/students/{rollNo}" ) public Student getStudent( @PathVariable ( "rollNo" ) String rollNo) { // in this method we can return // the student which we get from the api call. } |
In the above example getStudent method is annotated with @GetMapping annotation. This means that getStudent method will be called when an HTTP Get request is received at the /students/{rollNo} URL. Inside this url we have to specify the roll number for the student which we have to fetch.
Spring – @PostMapping and @GetMapping Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.