Discover how a simple annotation can save you hours of tedious coding and bugs!
Why @RestController annotation in Spring Boot? - Purpose & Use Cases
Imagine building a web service where you manually write code to handle HTTP requests, parse input, and format responses as JSON or XML for every endpoint.
Manually handling HTTP requests and responses is repetitive, error-prone, and makes your code messy and hard to maintain.
The @RestController annotation in Spring Boot automatically handles HTTP requests and converts your Java objects to JSON responses, simplifying API creation.
@Controller public class MyController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public ResponseEntity<String> hello() { return new ResponseEntity<>("Hello World", HttpStatus.OK); } }
@RestController public class MyController { @GetMapping("/hello") public String hello() { return "Hello World"; } }
It enables you to quickly build clean, maintainable REST APIs that automatically convert data to JSON without extra code.
Creating a backend for a mobile app that fetches user data as JSON, where @RestController handles requests and responses seamlessly.
Manual HTTP handling is complex and repetitive.
@RestController simplifies API development by automating request handling and response conversion.
This leads to cleaner, faster, and more maintainable code.
Practice
@RestController annotation in Spring Boot?Solution
Step 1: Understand the role of @RestController
@RestController is used to create REST APIs that return data directly, usually in JSON or XML format.Step 2: Compare with other options
Creating HTML views is handled by MVC controllers, defining service classes by @Service, and configuring database connections elsewhere in Spring Boot.Final Answer:
To create a controller that returns data directly as JSON or XML -> Option CQuick Check:
@RestController = returns data directly [OK]
- Confusing @RestController with @Service
- Thinking it renders HTML views
- Assuming it configures database
Solution
Step 1: Identify the correct annotation for REST controllers
@RestController is the correct annotation to create REST APIs in Spring Boot.Step 2: Check other annotations
@Controller is for MVC controllers returning views, @RestService is not a valid annotation, and @Service is for service classes.Final Answer:
@RestController public class MyController {} -> Option DQuick Check:
Correct REST controller syntax = @RestController public class MyController {} [OK]
- Using @Controller instead of @RestController
- Using non-existent @RestService annotation
- Confusing @Service with controller annotations
/hello endpoint?
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring!";
}
}Solution
Step 1: Understand @RestController behavior
@RestController returns the method's return value directly as the response body, usually JSON or plain text.Step 2: Analyze the method return
The method returns a String "Hello, Spring!" which will be sent as plain text in the response body.Final Answer:
A plain text response with the string "Hello, Spring!" -> Option BQuick Check:
@RestController + String return = plain text response [OK]
- Expecting an HTML page instead of data
- Thinking it causes 404 without mapping
- Assuming compilation error without reason
@RestController
public class UserController {
@GetMapping("/user")
public User getUser() {
User user = new User();
user.setName("Alice");
return user;
}
}
Assume User is a simple POJO with a name field and getters/setters.Solution
Step 1: Check @RestController effect
@RestController automatically adds @ResponseBody to all methods, so no need to add it explicitly.Step 2: Verify User class requirements
User is a POJO; it does not need @Entity unless used with database. Returning it will serialize to JSON automatically.Final Answer:
No error; code will return User object as JSON -> Option AQuick Check:
@RestController auto @ResponseBody = No error; code will return User object as JSON [OK]
- Adding unnecessary @ResponseBody on methods
- Confusing @Entity with serialization
- Thinking class-level @RequestMapping is mandatory
@RestController to achieve this?Solution
Step 1: Check @RestController and return type
@RestController public class UserApi { @GetMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Carol"); } } uses @RestController and returns a List<String>, which Spring Boot converts to JSON automatically.Step 2: Analyze other options
The snippet returning String sends a plain string, not a JSON list. The snippet using @Controller attempts to resolve a view name, not return JSON data. The snippet with void return type sends no response body, only prints to console.Final Answer:
@RestController public class UserApi { @GetMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Carol"); } } -> Option AQuick Check:
@RestController + List return = JSON list [OK]
- Using @Controller instead of @RestController for JSON
- Returning void or printing instead of returning data
- Returning plain string instead of list for JSON array
Ready to prove it?
Pass the test and this pattern moves unknown
