0
0
SpringbootConceptBeginner · 3 min read

@RestController in Spring: Definition, Usage, and Examples

@RestController is a Spring annotation that marks a class as a web controller where every method returns data directly as a response body. It combines @Controller and @ResponseBody, making it easy to create RESTful web services that send JSON or XML responses.
⚙️

How It Works

Imagine you want to build a simple web service that sends data like a list of books or user info. Normally, a web controller might return a web page, but with @RestController, the controller sends data directly to the client, like a JSON file.

This annotation tells Spring to skip the usual step of looking for a web page template and instead write the method's return value straight into the HTTP response. It’s like ordering food and getting it packed to go instead of eating at the restaurant.

Under the hood, @RestController is a shortcut that combines @Controller (which marks the class as a web controller) and @ResponseBody (which tells Spring to convert the return value to JSON or XML automatically).

💻

Example

This example shows a simple Spring Boot controller that returns a greeting message as JSON when you visit /hello.

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

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, world!";
    }
}
Output
"Hello, world!"
🎯

When to Use

Use @RestController when you want to build REST APIs that send data like JSON or XML to clients such as web browsers, mobile apps, or other servers. It is perfect for services that provide data rather than web pages.

Common use cases include:

  • Creating APIs for single-page applications (SPAs) or mobile apps.
  • Building microservices that communicate over HTTP.
  • Exposing data from databases or other sources in a simple, readable format.

Key Points

  • @RestController combines @Controller and @ResponseBody.
  • It automatically converts return values to JSON or XML.
  • It is used to build RESTful web services.
  • Methods inside return data directly, not views.

Key Takeaways

@RestController is for building REST APIs that return data directly.
It combines @Controller and @ResponseBody for simplicity.
Use it when you want to send JSON or XML responses instead of web pages.
It makes your code cleaner by removing the need to annotate each method with @ResponseBody.