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:
@RestController
combines@Controller
and@ResponseBody
âso every method returns data (not a view).@GetMapping("/hello")
wires up thesayHello()
method to handle GET requests at/hello
.- 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! đ