Spring Boot @GetMapping Example

1. Introduction

The @GetMapping annotation in Spring Boot is a convenient shortcut that acts as a specialized version of @RequestMapping. It narrows down the HTTP methods to only GET requests, making it a clear and concise way to handle these types of requests in web applications.

Key Points:

1. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

2. It is used to handle HTTP GET requests and is typically used for reading data.

3. @GetMapping can be used to map URL patterns, consume parameters, and even produce specific media types.

2. Implementation Steps

1. Create a Spring Boot project with the required web dependencies.

2. Define a controller class with the @RestController annotation.

3. Inside the controller, create a method and annotate it with @GetMapping, providing the URL pattern.

4. Optionally, use parameters within @GetMapping to fine-tune the request handling.

5. Run the application and access the defined endpoint to get the desired output.

3. Implementation Example

Here is the complete code that demonstrates the usage of @GetMapping annotation:
// Step 2: Define a controller class to handle GET requests
@RestController
public class SimpleController {

    // Step 3: Create a method to handle GET requests for the /hello endpoint
    @GetMapping("/hello")
    public String sayHello() {
        // Step 3: Return a response body directly
        return "Hello, World!";
    }
}

// Step 4: Define the main application class to run the Spring Boot application
@SpringBootApplication
public class GetMappingExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(GetMappingExampleApplication.class, args);
    }
}

Output:

Hello, World!

Explanation:

1. @RestController makes SimpleController a RESTful controller, suited for handling HTTP responses.

2. @GetMapping("/hello") specifically handles GET requests directed to the /hello path.

3. The sayHello method returns a String which will be the response body. Due to the @RestController annotation, there's no need for @ResponseBody.

4. GetMappingExampleApplication contains the main method, which uses SpringApplication.run to bootstrap and launch the application.

5. When a user sends a GET request to /hello, the sayHello method is invoked and responds with the text "Hello, World!".

6. The simplicity of @GetMapping makes it clear that sayHello is responsible for processing GET requests on /hello.


Comments