@GetMapping Spring boot
This article will cover @GetMapping
annotation in spring boot with example.
@GetMapping
annotation was introduced in Spring 4.3. It is applied over controller methods that handle HTTP GET requests.
Prior to 4.3, @RequestMapping
along with method
attribute as RequestMethod.GET
was used to configure GET request handler method as shown below
// before Spring 4.3 @RequestMapping(value="/users",method = RequestMethod.GET) public List<User> getUsers() { }
With @GetMapping
, above method can be replaced as
@GetMapping("/users") public List<User> getUsers() { }
@GetMapping
is followed by the string which signifies the URL for which this method will be exposed.
So, @GetMapping
is a shorthand annotation for @RequestMapping
.
Spring docs state,
@GetMapping
is a composed annotation that acts as a shortcut for@RequestMapping(method = RequestMethod.GET)
.
Enabling @GetMapping
@GetMapping
is added in spring 4.3. So, in order to use it you need to have below dependency as per the build tool
// MAVEN <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.0.11</version> </dependency> // GRADLE implementation 'org.springframework:spring-webmvc:6.0.11'
or if you are using Spring boot, then add below dependency
// MAVEN <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>3.1.2</version> </dependency> // GRADLE implementation 'org.springframework.boot:spring-boot-starter-web:3.1.2'
@GetMapping annotation example
Suppose you have a web application that accepts HTTP requests. You want to expose a URL that returns a list of all users.
Since the method returns something, it will be an HTTP GET request handler method.
It will be declared as
@GetMapping("users") public List<User> getUsers() { // return list of users }
Now, suppose there is another method that returns details of a user based on an id and this id is received from the URL.
Request handler method will be annotated with @GetMapping
as shown below
@GetMapping("users/{id}") public User getUser(@PathVariable Integer id) { // return detail of user }
This method will be invoked when the URL being accessed is of the format user/1
.
Note that the method parameter that receives the id
, is annotated with @PathVariable annotation and {id}
after the URL in @GetMapping
denotes that this value will be received from the URL.
So, in this case the method parameter id
will automatically be populated with 1.