0
0
Spring Bootframework~5 mins

@RestController annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @RestController annotation tells Spring Boot to handle web requests and send back data, usually in JSON format, instead of a web page.

When building a web API that sends data to a client app like a mobile app or frontend JavaScript.
When you want to create a simple service that returns JSON or XML responses.
When you do not need to return HTML views but only data.
When you want to quickly create RESTful web services without extra configuration.
Syntax
Spring Boot
@RestController
public class MyController {
    // handler methods
}
It combines @Controller and @ResponseBody, so you don't need to add @ResponseBody on each method.
Use it on classes that handle HTTP requests and return data directly.
Examples
This example creates a simple endpoint /hello that returns plain text.
Spring Boot
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}
This example returns a User object as JSON automatically.
Spring Boot
@RestController
public class UserController {
    @GetMapping("/user")
    public User getUser() {
        return new User("Alice", 30);
    }
}
Sample Program

This Spring Boot controller listens for GET requests at /greet and returns a simple greeting string as the response body.

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

@RestController
public class GreetingController {

    @GetMapping("/greet")
    public String greet() {
        return "Hello from Spring Boot!";
    }
}
OutputSuccess
Important Notes

Remember that @RestController automatically converts return values to JSON or other formats using message converters.

If you want to return HTML views, use @Controller instead.

Use @GetMapping, @PostMapping, etc., inside the class to handle specific HTTP methods.

Summary

@RestController makes it easy to create REST APIs by returning data directly.

It combines controller and response body behavior in one annotation.

Use it when you want to send JSON or other data formats, not HTML pages.