Snippet: Quick @RestController + @GetMapping Example 🐵✨

Just drop this into your Spring Boot project—no extra bells and whistles. It’ll expose a simple HTTP GET endpoint at /hello.

javaCopyEditpackage com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController            // ← Marks this class as a RESTful controller
public class HelloController {

    @GetMapping("/hello")  // ← Maps HTTP GET requests on "/hello"
    public String sayHello() {
        return "🐒 Hello from Spring Boot!";
    }
}

How it works:

  1. @RestController combines @Controller and @ResponseBody—so every method returns data (not a view).
  2. @GetMapping("/hello") wires up the sayHello() method to handle GET requests at /hello.
  3. The method returns a plain String, which Spring Boot auto-converts to an HTTP response body.

Monkey-Proof Tips:

  • Keep each controller focused on a single “resource” or endpoint group.
  • For JSON, return an object or record instead of raw String: javaCopyEditrecord Greeting(String message) {} @GetMapping("/hello") public Greeting sayHello() { return new Greeting("Hello, Spring Boot!"); }
  • Want path parameters? Swap in @GetMapping("/hello/{name}") and use @PathVariable String name.

Now you’ve got a copy-paste-ready snippet for your next Spring Boot blog post or tutorial! 🙌

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *