Spring Boot Annotations
Comprehensive reference for all key Spring Boot annotations: web, data, security, testing
- Identify the purpose of every common Spring Boot annotation
- Apply @RestController, @RequestMapping, @PathVariable, @RequestBody correctly
- Use Spring's stereotype annotations: @Component, @Service, @Repository
Spring Boot Series | Concept and Coding
Table of Contents
- How HTTP Requests Reach Your Code — The Big Picture
- @Controller
- @RestController
- @Controller vs @RestController
- @ResponseBody
- @RequestMapping
- @GetMapping, @PostMapping and Shorthand Annotations
- @RequestParam
- Type Conversion and Custom Property Editors (@InitBinder)
- @PathVariable
- @RequestBody
- ResponseEntity
- Putting It All Together — Full Example
- Key Diagrams
- Interview Notes
- Common Mistakes
- Summary Cheat Sheet
1. How HTTP Requests Reach Your Code The Big Picture
Overview
Before diving into individual annotations, it's critical to understand how Spring Boot routes an incoming HTTP request to the correct Java method. This routing mechanism is called the Dispatcher Servlet pattern.
The Request Flow
When a user or client sends an HTTP request (e.g., GET /api/fetchUser), this is what happens internally:
1User/Client2 │3 │ HTTP Request: GET /api/fetchUser4 ▼5DispatcherServlet ← Front controller — receives ALL requests6 │7 │ "Which controller can handle this?"8 ▼9HandlerMapping ← Scans all @Controller/@RestController classes10 │ and their @RequestMapping annotations11 │ "SampleController.getUserDetails() handles GET /api/fetchUser"12 ▼13SampleController ← Your class with business logic14 │15 │ Executes the method, gets a result16 ▼17HttpMessageConverter ← Converts Java object → JSON/XML18 │19 ▼20HTTP Response → User/ClientWhat Annotations Enable This
The annotations covered in this guide are what tell Spring Boot how to build the HandlerMapping table:
| Annotation | Role in Request Handling |
|---|---|
@Controller / @RestController | Marks a class as eligible to handle HTTP requests |
@RequestMapping / @GetMapping etc. | Maps a specific URL + HTTP method to a specific Java method |
@RequestParam | Extracts query parameters from the URL |
@PathVariable | Extracts values embedded in the URL path |
@RequestBody | Binds the request body (JSON/XML) to a Java object |
ResponseEntity | Gives full control over the HTTP response (status, headers, body) |
2. @Controller
Overview
@Controller is a Spring stereotype annotation that marks a class as a web controller — meaning it is responsible for handling incoming HTTP requests.
Why This Exists
The DispatcherServlet needs to know which classes in your application are capable of handling HTTP requests. Among potentially hundreds of classes, only those annotated with @Controller (or @RestController) are considered for request handling.
Definition
@Controllertells Spring Boot: "This class may contain methods that handle HTTP requests. Include it in the handler mapping scan."
Internal Working
When Spring Boot starts up:
- It performs component scanning — scanning all classes in the application
- Classes annotated with
@Controllerare registered in the ApplicationContext as beans - Spring's
RequestMappingHandlerMappinginspects these beans for@RequestMappingannotations - A mapping table is built: URL + HTTP method → Java method
This scanning and registration happens through Java Reflection — Spring reads annotations at runtime and uses them to configure routing.
Syntax
1import org.springframework.stereotype.Controller;2
3@Controller4public class SampleController {5 // Handler methods go here6}Important Behaviour Without @ResponseBody
@Controller alone does NOT automatically treat method return values as HTTP responses. If you return a String from a method in a plain @Controller, Spring Boot treats it as a View name and tries to resolve it to a template file (e.g., hello.jsp, hello.html).
1@Controller2public class SampleController {3
4 @GetMapping("/hello")5 public String sayHello() {6 return "hello"; // Spring treats this as: find a view named "hello.jsp" or "hello.html"7 }8}If no matching view is found, Spring throws an error. This behaviour is intentional — @Controller was designed for server-side rendering applications (like JSP or Thymeleaf) where you return view names.
@Controller was the original annotation before REST APIs became common. In modern Spring Boot REST API development, @RestController is almost always used instead.3. @RestController
Overview
@RestController is a composed annotation — it is a shortcut that combines two annotations into one:
1@RestController = @Controller + @ResponseBodyWhy This Exists
In REST API development, every single method in a controller returns data (JSON/XML) — not a view name. Writing @ResponseBody on every method is tedious and repetitive. @RestController applies @ResponseBody at the class level, so all methods inherit it automatically.
Definition
@RestControllertells Spring Boot: "This class handles HTTP requests, AND all its methods return data that should be sent directly as HTTP response bodies — never treated as view names."
Syntax
1import org.springframework.web.bind.annotation.RestController;2
3@RestController4public class SampleController {5 // Every method's return value is automatically an HTTP response body6}Code Example
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @GetMapping("/user")6 public String getUser() {7 return "Shreyansh"; // Sent as HTTP response body: Shreyansh8 }9
10 @GetMapping("/message")11 public String getMessage() {12 return "Hello World"; // Sent as HTTP response body: Hello World13 }14}Shreyansh
No @ResponseBody needed on either method — @RestController handles it for the whole class.
4. @Controller vs @RestController
Side-by-Side Comparison
1// ---- Using @Controller ----2@Controller3public class ViewController {4
5 @GetMapping("/page")6 public String showPage() {7 return "home"; // Spring looks for home.jsp / home.html — renders a VIEW8 }9
10 @GetMapping("/data")11 @ResponseBody // ← Must add this explicitly on each method12 public String getData() {13 return "some data"; // Now treated as HTTP response, not a view14 }15}1// ---- Using @RestController ----2@RestController3public class ApiController {4
5 @GetMapping("/page")6 public String showPage() {7 return "home"; // Sent as HTTP response body (text "home") — NOT a view lookup8 }9
10 @GetMapping("/data")11 public String getData() {12 return "some data"; // Sent as HTTP response body — no @ResponseBody needed13 }14}Comparison Table
| Feature | @Controller | @RestController |
|---|---|---|
| Marks class for request handling | ✅ | ✅ |
| Returns view names by default | ✅ | ❌ |
Includes @ResponseBody | ❌ (must add manually) | ✅ (built-in) |
| Used for | Server-side rendering (JSP, Thymeleaf) | REST APIs |
| Convenience for REST APIs | Low | High |
@RestController. Only use @Controller if you are doing server-side HTML rendering with a template engine.5. @ResponseBody
Overview
@ResponseBody is the annotation that tells Spring Boot: "Do not treat this method's return value as a view name. Treat it as the actual HTTP response body and send it directly to the client."
Why This Exists
Spring's default behaviour for @Controller methods is to look up a view. @ResponseBody overrides this default and instructs Spring to use an HttpMessageConverter to serialize the return value (e.g., convert a Java object to JSON) and write it to the HTTP response.
Definition
@ResponseBodyinstructs Spring to bind the return value of a method to the HTTP response body, bypassing view resolution entirely.
Syntax
1// On a method inside a @Controller class2@Controller3public class SampleController {4
5 @GetMapping("/data")6 @ResponseBody // ← Overrides view resolution for this method7 public String fetchData() {8 return "fetch user details of Shreyansh";9 }10}What Happens Without @ResponseBody (inside @Controller)
1@Controller2public class SampleController {3
4 @GetMapping("/fetchUser")5 public String fetchUserDetails() {6 return "fetch user details of Shreyansh";7 }8}Spring Boot tries to find a view file named fetch user details of Shreyansh.jsp (or .html). It fails and throws:
1javax.servlet.ServletException: Could not resolve view with name2'fetch user details of Shreyansh'Internally How @ResponseBody Works
When @ResponseBody is present, Spring:
- Inspects the method's return type
- Looks at the
Acceptheader in the HTTP request (e.g.,application/json) - Selects an appropriate
HttpMessageConverter(e.g.,MappingJackson2HttpMessageConverterfor JSON) - Serializes the Java return value to the appropriate format
- Writes the serialized content to the
HttpServletResponseoutput stream
6. @RequestMapping
Overview
@RequestMapping is the core mapping annotation in Spring MVC. It maps HTTP requests to specific handler methods in controller classes. Every other mapping annotation (@GetMapping, @PostMapping, etc.) is built on top of @RequestMapping.
Why This Exists
The DispatcherServlet needs to know which method to call for which URL and HTTP method combination. @RequestMapping provides this configuration.
Definition
@RequestMappingmaps a web request (URL path + HTTP method + other constraints) to a specific handler method or class.
Syntax On a Method
1@RequestMapping(path = "/fetchUser", method = RequestMethod.GET)2public String getUserDetails() {3 // handle GET /fetchUser4}Syntax On a Class (Base Path)
1@RestController2@RequestMapping("/api") // ← All methods in this class use "/api" as base3public class UserController {4
5 @RequestMapping(path = "/fetchUser", method = RequestMethod.GET)6 public String fetchUser() {7 // Handles: GET /api/fetchUser8 }9
10 @RequestMapping(path = "/saveUser", method = RequestMethod.POST)11 public String saveUser() {12 // Handles: POST /api/saveUser13 }14}Parameters of @RequestMapping
| Parameter | Alias | Description | Example |
|---|---|---|---|
path | value | URL path to match | path = "/fetchUser" |
method | — | HTTP method to match | method = RequestMethod.GET |
params | — | Required query parameters | params = "version=2" |
headers | — | Required HTTP headers | headers = "X-Custom=true" |
consumes | — | Required Content-Type | consumes = "application/json" |
produces | — | Response Content-Type | produces = "application/json" |
path and value are aliases for each other. path = "/fetchUser" and value = "/fetchUser" are identical. Most developers prefer path for readability since it clearly communicates intent.Class-Level vs Method-Level Mapping
When multiple endpoints share a common path prefix:
1// ❌ Without class-level mapping — repetitive2@RestController3public class UserController {4
5 @RequestMapping(path = "/api/fetchUser", method = RequestMethod.GET)6 public String fetchUser() { ... }7
8 @RequestMapping(path = "/api/saveUser", method = RequestMethod.POST)9 public String saveUser() { ... }10
11 @RequestMapping(path = "/api/deleteUser", method = RequestMethod.DELETE)12 public String deleteUser() { ... }13}1// ✅ With class-level mapping — clean and DRY2@RestController3@RequestMapping("/api") // ← Common prefix defined once4public class UserController {5
6 @RequestMapping(path = "/fetchUser", method = RequestMethod.GET)7 public String fetchUser() { ... } // Handles: GET /api/fetchUser8
9 @RequestMapping(path = "/saveUser", method = RequestMethod.POST)10 public String saveUser() { ... } // Handles: POST /api/saveUser11
12 @RequestMapping(path = "/deleteUser", method = RequestMethod.DELETE)13 public String deleteUser() { ... } // Handles: DELETE /api/deleteUser14}The class-level path is prepended to the method-level path. If class path is /api and method path is /fetchUser, the final mapped URL is /api/fetchUser.
7. @GetMapping, @PostMapping and Shorthand Annotations
Overview
Spring provides shorthand composed annotations for each common HTTP method. These are convenience wrappers around @RequestMapping with the HTTP method pre-set.
The Complete Set
| Annotation | Equivalent To | HTTP Method | Typical Use |
|---|---|---|---|
@GetMapping | @RequestMapping(method = RequestMethod.GET) | GET | Retrieve data |
@PostMapping | @RequestMapping(method = RequestMethod.POST) | POST | Create new resource |
@PutMapping | @RequestMapping(method = RequestMethod.PUT) | PUT | Replace entire resource |
@PatchMapping | @RequestMapping(method = RequestMethod.PATCH) | PATCH | Partially update resource |
@DeleteMapping | @RequestMapping(method = RequestMethod.DELETE) | DELETE | Delete resource |
Code Example
1@RestController2@RequestMapping("/api")3public class UserController {4
5 // GET /api/users6 @GetMapping("/users")7 public String getAllUsers() {8 return "List of all users";9 }10
11 // POST /api/users12 @PostMapping("/users")13 public String createUser(@RequestBody User user) {14 return "User created: " + user.getUsername();15 }16
17 // PUT /api/users/118 @PutMapping("/users/{id}")19 public String updateUser(@PathVariable int id, @RequestBody User user) {20 return "User " + id + " updated";21 }22
23 // DELETE /api/users/124 @DeleteMapping("/users/{id}")25 public String deleteUser(@PathVariable int id) {26 return "User " + id + " deleted";27 }28}Why Prefer Shorthand Annotations?
1// Verbose — using @RequestMapping2@RequestMapping(path = "/users", method = RequestMethod.GET)3public String getUsers() { ... }4
5// Clean — using @GetMapping6@GetMapping("/users")7public String getUsers() { ... }@GetMapping is preferred because:
- Less code to write
- Intent is immediately obvious from the annotation name
- Reduces risk of accidentally setting the wrong HTTP method
@GetMapping, @PostMapping, etc. are almost always used instead of the verbose @RequestMapping(method = ...) form. Reserve @RequestMapping for class-level base path declarations.8. @RequestParam
Overview
@RequestParam is used to extract query parameters from the URL and bind them to controller method parameters.
What Are Query Parameters?
Query parameters appear after the ? in a URL, separated by &:
1https://example.com/api/fetchUser?firstName=Shreyansh&lastName=Gupta&age=252 ↑───────────────── ↑────────────── ↑────3 Param 1 Param 2 Param 3Each key=value pair separated by & is one query parameter.
Definition
@RequestParambinds the value of a URL query parameter to a Java method parameter in a controller method.
Syntax
1@GetMapping("/fetchUser")2public String getUserDetails(3 @RequestParam(name = "firstName") String firstName,4 @RequestParam(name = "lastName", required = false) String lastName,5 @RequestParam(name = "age") int age) {6
7 return "User: " + firstName + " " + lastName + ", Age: " + age;8}Parameters of @RequestParam
| Parameter | Default | Description |
|---|---|---|
name / value | — | The name of the query parameter in the URL |
required | true | If true, the request fails if this param is absent |
defaultValue | — | Value to use if the parameter is absent (makes it effectively optional) |
name and value are aliases in @RequestParam, just like in @RequestMapping.Full Code Example
1@RestController2@RequestMapping("/api")3public class SampleController {4
5 @GetMapping("/user")6 public String fetchUserDetails(7 @RequestParam(name = "firstName") String firstName, // required by default8 @RequestParam(name = "lastName", required = false) String lastName) { // optional9
10 return "Fetch user details of " + firstName + " and " + lastName;11 }12}Scenario 1 All required params present
1GET /api/user?firstName=Shreyansh&lastName=GuptaFetch user details of Shreyansh and Gupta
Scenario 2 Optional param absent
1GET /api/user?firstName=ShreyanshFetch user details of Shreyansh and null
lastName is null because it was marked required = false and not provided.
Scenario 3 Required param missing
1GET /api/user?lastName=GuptaHTTP 400 Bad Request MissingServletRequestParameterException: Required request parameter 'firstName' is not present
The request is rejected because firstName is required but missing.
Using `defaultValue`
1@GetMapping("/user")2public String fetchUser(3 @RequestParam(name = "page", defaultValue = "1") int page,4 @RequestParam(name = "size", defaultValue = "10") int size) {5
6 return "Page: " + page + ", Size: " + size;7}1GET /api/user → Page: 1, Size: 10 (defaults used)2GET /api/user?page=3 → Page: 3, Size: 10 (only size uses default)Automatic Type Conversion
Spring Boot automatically converts the String representation of query parameters to the declared Java type of the method parameter:
1@GetMapping("/user")2public String fetchUser(3 @RequestParam("age") int age, // String "25" → int 254 @RequestParam("active") boolean active, // String "true" → boolean true5 @RequestParam("score") double score) { // String "98.6" → double 98.66 ...7}Supported automatic conversions:
| URL String Value | Java Type | Example |
|---|---|---|
"25" | int / Integer | ?age=25 |
"true" / "false" | boolean / Boolean | ?active=true |
"98.6" | double / Double | ?score=98.6 |
"hello" | String | ?name=hello |
"RED" | enum Color | ?color=RED |
?age=abc and the method expects int age, Spring throws a MethodArgumentTypeMismatchException (HTTP 400). Always validate or handle this gracefully.9. Type Conversion and Custom Property Editors (@InitBinder)
Overview
For cases where automatic type conversion is insufficient — for example, normalizing string casing, cleaning input, or converting to a complex custom type — Spring provides a Custom Property Editor mechanism, configurable via @InitBinder.
Why This Exists
Automatic type conversion handles primitives and standard types. But what if you need to:
- Trim whitespace from a string input
- Convert all input to lowercase regardless of what the user sends
- Parse a custom date format string into a
LocalDateobject - Map a raw string like
"23/04/1999"to aDateobject
These scenarios require custom logic that runs before the value is bound to the method parameter.
@InitBinder
@InitBinder marks a method inside a controller that configures a WebDataBinder for that controller. The binder runs before every handler method in the controller, applying registered custom editors to parameters.
Syntax
1@InitBinder2public void initBinder(WebDataBinder binder) {3 // Register custom editors here4}Complete Custom Property Editor Example
Goal: No matter what case the user sends for firstName (e.g., SHREYANSH, shreyansh, ShReYaNsH), always normalize it to lowercase and trimmed.
Step 1 Create the Custom Property Editor
1import java.beans.PropertyEditorSupport;2
3public class FirstNamePropertyEditor extends PropertyEditorSupport {4
5 @Override6 public void setAsText(String text) {7 // text is the raw String value from the URL8 // Apply custom transformation before binding9 String normalized = text.trim().toLowerCase();10 setValue(normalized); // setValue() sets the final value that gets bound to the parameter11 }12}Line-by-line explanation:
extends PropertyEditorSupport— required; this is the base class Spring uses for custom editorssetAsText(String text)— called with the raw URL string valuetext.trim().toLowerCase()— our custom logic: remove spaces, convert to lowercasesetValue(normalized)— sets the transformed value; Spring binds this to the method parameter
Step 2 Register the Editor with @InitBinder
1@RestController2@RequestMapping("/api")3public class SampleController {4
5 @InitBinder6 public void initBinder(WebDataBinder binder) {7 binder.registerCustomEditor(8 String.class, // Target type: the method param is a String9 "firstName", // Only apply to the param named "firstName"10 new FirstNamePropertyEditor() // Our custom editor11 );12 }13
14 @GetMapping("/user")15 public String fetchUser(16 @RequestParam("firstName") String firstName,17 @RequestParam(name = "lastName", required = false) String lastName) {18
19 return "User: " + firstName + ", " + lastName;20 }21}Step 3 Test It
1GET /api/user?firstName=SHREYANSH&lastName=GuptaWithout editor: firstName = "SHREYANSH" With editor: firstName = "shreyansh"
Output:
1User: shreyansh, GuptaHow @InitBinder Works Execution Flow
Custom Object Type Conversion
@InitBinder also supports converting strings to complex objects:
1public class DatePropertyEditor extends PropertyEditorSupport {2
3 private static final DateTimeFormatter FORMATTER =4 DateTimeFormatter.ofPattern("dd/MM/yyyy");5
6 @Override7 public void setAsText(String text) {8 LocalDate date = LocalDate.parse(text.trim(), FORMATTER);9 setValue(date);10 }11}1@InitBinder2public void initBinder(WebDataBinder binder) {3 binder.registerCustomEditor(LocalDate.class, new DatePropertyEditor());4}5
6@GetMapping("/events")7public String getEvents(@RequestParam("date") LocalDate date) {8 return "Events on: " + date; // date is a proper LocalDate object9}1GET /api/events?date=23/04/19992→ Events on: 1999-04-2310. @PathVariable
Overview
@PathVariable extracts values that are embedded directly in the URL path (not after ?) and binds them to controller method parameters.
Path Variable vs Query Parameter
1Query Parameter: /api/fetchUser?id=123452 ↑3 After "?" — use @RequestParam4
5Path Variable: /api/fetchUser/123456 ↑7 Part of the path — use @PathVariableWhy This Exists
RESTful API design convention uses path variables for resource identifiers — the ID of the specific resource you're operating on. For example:
GET /api/users/42— get user with ID 42DELETE /api/users/42— delete user with ID 42GET /api/users/42/orders/7— get order 7 of user 42
Definition
@PathVariableextracts a dynamic value from a URI template variable (denoted by{variableName}in the path) and binds it to a method parameter.
Syntax
1// In the path: {firstName} is a URI template variable2@GetMapping("/fetchUser/{firstName}")3public String fetchUser(@PathVariable("firstName") String firstName) {4 return "Fetching user: " + firstName;5}The {firstName} in the mapping path is a placeholder. Whatever value appears at that position in the URL is extracted and bound to the method parameter.
Complete Code Example
1@RestController2@RequestMapping("/api")3public class SampleController {4
5 // Single path variable6 @GetMapping("/fetchUser/{firstName}")7 public String fetchUser(@PathVariable("firstName") String firstName) {8 return "Fetching details for: " + firstName;9 }10
11 // Multiple path variables12 @GetMapping("/users/{userId}/orders/{orderId}")13 public String getOrder(14 @PathVariable("userId") int userId,15 @PathVariable("orderId") int orderId) {16 return "Order " + orderId + " for user " + userId;17 }18}Calling the API
1GET /api/fetchUser/Shreyansh2→ Fetching details for: Shreyansh3
4GET /api/fetchUser/JohnDoe5→ Fetching details for: JohnDoe6
7GET /api/users/42/orders/78→ Order 7 for user 42Shorthand When Variable Name Matches Parameter Name
If the URI template variable name matches the Java parameter name exactly, you can omit the name argument:
1// Explicit2@GetMapping("/users/{userId}")3public String getUser(@PathVariable("userId") int userId) { ... }4
5// Shorthand (name inferred from parameter name)6@GetMapping("/users/{userId}")7public String getUser(@PathVariable int userId) { ... } // "userId" inferred@PathVariable vs @RequestParam Summary
| Aspect | @PathVariable | @RequestParam |
|---|---|---|
| URL position | Inside the path | After ? |
| Example URL | /api/users/42 | /api/users?id=42 |
| REST convention | Resource identifiers | Filters, pagination, sorting |
| Required | Always present (it's in the path) | Optional (with required=false) |
| URL looks like | /api/users/{id} | /api/users?id=... |
11. @RequestBody
Overview
@RequestBody binds the body of an HTTP request (typically JSON or XML) to a Java object — the controller method parameter.
Why This Exists
When a client sends a POST, PUT, or PATCH request, it typically includes a request body containing the data to be created or updated. This data arrives as a JSON string. @RequestBody tells Spring to convert that JSON into a Java object automatically.
Definition
@RequestBodyinstructs Spring to deserialize the HTTP request body into the annotated method parameter using anHttpMessageConverter(typically Jackson for JSON).
Syntax
1@PostMapping("/saveUser")2public String saveUser(@RequestBody User user) {3 return "Saved: " + user.getUsername();4}The Conversion Process
1HTTP Request Body (JSON String) Java Object2──────────────────────────────── ──────────────────────────3{ User {4 "username": "shreyansh", ──────▶ String username = "shreyansh"5 "email": "s@example.com" String email = "s@example.com"6} }Spring uses the Jackson library (included automatically in Spring Boot) to perform this deserialization.
Complete Code Example
The Domain Class (POJO)
1public class User {2
3 private String username;4 private String email;5
6 // Getters and setters are REQUIRED — Jackson uses them to set values7 public String getUsername() { return username; }8 public void setUsername(String username) { this.username = username; }9
10 public String getEmail() { return email; }11 public void setEmail(String email) { this.email = email; }12}The Controller
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @PostMapping("/saveUser")6 public String saveUser(@RequestBody User user) {7 return "Saved user: " + user.getUsername() + ", Email: " + user.getEmail();8 }9}HTTP Request (e.g., from Postman)
1POST /api/saveUser2Content-Type: application/json3
4{5 "username": "shreyansh",6 "email": "shreyansh@example.com"7}Saved user: shreyansh, Email: shreyansh@example.com
JSON Key Mismatch @JsonProperty
By default, Jackson maps JSON keys to Java field names by exact name match. If names differ, use @JsonProperty:
1// JSON coming from the client2{3 "user_name": "shreyansh",4 "email": "s@example.com"5}1public class User {2
3 @JsonProperty("user_name") // ← Maps JSON key "user_name" to this field4 private String username; // ← Java field name is "username" (different)5
6 private String email; // ← "email" matches exactly — no annotation needed7
8 // Getters and setters...9}Without @JsonProperty("user_name"), Jackson looks for a JSON key "username" (matching the field name), doesn't find it, and username remains null.
How Jackson Mapping Works Internally
- Spring receives the HTTP request with
Content-Type: application/json - Spring selects
MappingJackson2HttpMessageConverterto handle it - Jackson reads the JSON string from the request body
- For each JSON key, Jackson looks for a matching setter method in the Java class (e.g., key
"email"→ callssetEmail(...)) - If
@JsonPropertyis present, the annotation value is used for matching instead of the field name - The fully populated Java object is passed to the controller method
@Data annotation.12. ResponseEntity
Overview
ResponseEntity gives you complete control over the HTTP response — including the status code, response headers, and response body — all from within a controller method.
The Three Parts of an HTTP Response
1HTTP/1.1 200 OK ← Status Line (Status Code + Reason Phrase)2Content-Type: application/json ← Response Headers3X-Custom-Header: value4
5{ ← Response Body6 "username": "shreyansh"7}| Part | Controlled by |
|---|---|
| Body | @ResponseBody / @RestController return value |
| Status code | Default 200 OK (or @ResponseStatus) |
| Headers | Not easily controlled without ResponseEntity |
ResponseEntity wraps all three parts into one object you return from your method.
Definition
ResponseEntityrepresents the complete HTTP response — status code, headers, and body. The generic typeTis the type of the response body.
Syntax
1// Full constructor2ResponseEntity<String> response = new ResponseEntity<>(3 "response body", // body4 HttpStatus.OK // status code5);6
7// Builder pattern (preferred)8ResponseEntity.ok("response body"); // 200 OK with body9ResponseEntity.status(HttpStatus.CREATED).body("created"); // 201 Created with body10ResponseEntity.notFound().build(); // 404 Not Found, no bodyComplete Code Example
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @GetMapping("/user/{id}")6 public ResponseEntity<String> getUser(@PathVariable int id) {7
8 if (id <= 0) {9 // Return 400 Bad Request10 return ResponseEntity11 .status(HttpStatus.BAD_REQUEST)12 .body("Invalid user ID: " + id);13 }14
15 String userData = fetchFromDatabase(id); // your business logic16
17 if (userData == null) {18 // Return 404 Not Found19 return ResponseEntity20 .status(HttpStatus.NOT_FOUND)21 .body("User not found");22 }23
24 // Return 200 OK with data25 return ResponseEntity26 .ok(userData);27 }28
29 @PostMapping("/user")30 public ResponseEntity<String> createUser(@RequestBody User user) {31 // ... save logic ...32
33 // Return 201 Created with custom header34 return ResponseEntity35 .status(HttpStatus.CREATED)36 .header("X-User-Created", user.getUsername()) // custom header37 .body("User created successfully");38 }39
40 private String fetchFromDatabase(int id) {41 return "Shreyansh"; // placeholder42 }43}Common HTTP Status Codes
| Code | Name | When to Use |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST (resource created) |
| 204 | No Content | Successful DELETE (no body to return) |
| 400 | Bad Request | Invalid input, validation failure |
| 401 | Unauthorized | Not authenticated |
| 403 | Forbidden | Authenticated but not authorized |
| 404 | Not Found | Resource doesn't exist |
| 500 | Internal Server Error | Unexpected server error |
What @RestController Returns vs ResponseEntity
1// Without ResponseEntity — Spring creates it internally2@RestController3public class Controller {4
5 @GetMapping("/data")6 public String getData() {7 return "hello"; // Spring wraps this in ResponseEntity<String> with 200 OK8 }9}10
11// With ResponseEntity — you control everything explicitly12@RestController13public class Controller {14
15 @GetMapping("/data")16 public ResponseEntity<String> getData() {17 return ResponseEntity18 .status(HttpStatus.OK)19 .header("X-App-Version", "1.0")20 .body("hello");21 }22}When you return a plain value from a @RestController, Spring internally creates a ResponseEntity with:
- Status: 200 OK
- Body: your return value (serialized)
- No custom headers
ResponseEntity is used when you need anything beyond this default.
ResponseEntity in all REST API controllers. It makes your API responses explicit, predictable, and easier to test.13. Putting It All Together Full Example
Below is a complete, realistic controller that uses all the annotations covered:
1import org.springframework.http.HttpStatus;2import org.springframework.http.ResponseEntity;3import org.springframework.web.bind.annotation.*;4
5@RestController6@RequestMapping("/api/users") // Base path for all endpoints in this controller7public class UserController {8
9 // ─── GET /api/users/{id} ─────────────────────────────────────────────────10 // Uses @PathVariable to extract the user ID from the URL11 @GetMapping("/{id}")12 public ResponseEntity<String> getUserById(@PathVariable("id") int id) {13 if (id <= 0) {14 return ResponseEntity.status(HttpStatus.BAD_REQUEST)15 .body("ID must be positive");16 }17 return ResponseEntity.ok("User with ID: " + id);18 }19
20 // ─── GET /api/users?firstName=X&lastName=Y ───────────────────────────────21 // Uses @RequestParam to extract query parameters22 @GetMapping("/search")23 public ResponseEntity<String> searchUser(24 @RequestParam("firstName") String firstName,25 @RequestParam(name = "lastName", required = false) String lastName) {26
27 String result = "Searching for: " + firstName;28 if (lastName != null) result += " " + lastName;29 return ResponseEntity.ok(result);30 }31
32 // ─── POST /api/users ─────────────────────────────────────────────────────33 // Uses @RequestBody to deserialize the JSON body into a User object34 @PostMapping35 public ResponseEntity<String> createUser(@RequestBody User user) {36 // Save user logic here...37 return ResponseEntity.status(HttpStatus.CREATED)38 .body("Created user: " + user.getUsername());39 }40
41 // ─── DELETE /api/users/{id} ───────────────────────────────────────────────42 @DeleteMapping("/{id}")43 public ResponseEntity<Void> deleteUser(@PathVariable("id") int id) {44 // Delete logic here...45 return ResponseEntity.noContent().build(); // 204 No Content46 }47}14. Key Diagrams
Full Annotation Architecture
@Controller vs @RestController Decision
URL Parameter Types Comparison
Request Body Processing
ResponseEntity vs Plain Return
15. Interview Notes
Common Interview Questions and Answers
Q1: What is the difference between @Controller and @RestController?
Answer:
@Controllermarks a class as a request handler. By default, return values are treated as view names for server-side rendering.@RestController=@Controller+@ResponseBody. Return values are treated as HTTP response bodies (serialized to JSON/XML). No view resolution happens.- Use
@Controllerfor MVC apps with HTML templates (Thymeleaf, JSP). Use@RestControllerfor REST APIs.
Q2: What does @ResponseBody do?
Answer: It tells Spring to write the method's return value directly to the HTTP response body, bypassing view resolution. With @RestController, @ResponseBody is applied implicitly on all methods.
Q3: What is the difference between @RequestParam and @PathVariable?
@RequestParam | @PathVariable | |
|---|---|---|
| URL location | After ? | Inside path |
| Example | /users?id=42 | /users/42 |
| Optional | Yes (required=false) | No (always in URL) |
| Use case | Filters, pagination | Resource IDs |
Q4: What is @RequestMapping and how does @GetMapping differ from it?
Answer: @RequestMapping is the base annotation for mapping HTTP requests to handler methods. It supports all HTTP methods via the method attribute. @GetMapping is a shorthand for @RequestMapping(method = RequestMethod.GET). Similarly, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping exist for other methods.
Q5: How does Spring convert JSON to a Java object in @RequestBody?
Answer: Spring uses HttpMessageConverter — specifically MappingJackson2HttpMessageConverter (Jackson library, auto-configured in Spring Boot). Jackson matches JSON keys to Java field names and uses setter methods to populate the object. For mismatched names, @JsonProperty annotation specifies the JSON key to use.
Q6: What is ResponseEntity and when would you use it?
Answer: ResponseEntity represents the entire HTTP response — status code, headers, and body. Use it when you need to:
- Return a non-200 status code (e.g., 201 Created, 404 Not Found)
- Add custom response headers
- Return different status codes based on business logic
When you return a plain object from @RestController, Spring internally creates a ResponseEntity with status 200 and no custom headers.
Q7: What is @InitBinder used for?
Answer: @InitBinder marks a method that configures a WebDataBinder for the controller. It's used to register custom property editors that pre-process request parameters before they are bound to method parameters. Common use cases: normalizing input, custom date parsing, complex type conversion.
Q8: Can @RequestMapping be placed at both class and method level? What happens?
Answer: Yes. Class-level @RequestMapping defines a base path that is prepended to all method-level paths. For example:
- Class:
@RequestMapping("/api") - Method:
@GetMapping("/users") - Result: Maps to
GET /api/users
Q9: What happens if `required = true` (default) and the @RequestParam is not provided?
Answer: Spring throws MissingServletRequestParameterException, resulting in an HTTP 400 Bad Request response.
Q10: What is the role of @JsonProperty?
Answer: @JsonProperty is a Jackson annotation that maps a JSON key name to a Java field when the names don't match. Example: JSON key "user_name" maps to Java field username with @JsonProperty("user_name").
16. Common Mistakes
Mistake 1 Using @Controller for REST APIs Without @ResponseBody
1// ❌ Wrong — returns view name, not JSON2@Controller3public class UserController {4
5 @GetMapping("/user")6 public String getUser() {7 return "Shreyansh"; // Spring looks for "Shreyansh.jsp" — 500 error8 }9}1// ✅ Correct — use @RestController for REST APIs2@RestController3public class UserController {4
5 @GetMapping("/user")6 public String getUser() {7 return "Shreyansh"; // Sent as HTTP response body8 }9}Mistake 2 Forgetting Getters/Setters in @RequestBody Classes
1// ❌ Jackson can't set values without setters2public class User {3 private String username;4 private String email;5 // No getters or setters!6}7// Result: username = null, email = null after @RequestBody binding1// ✅ Always include getters and setters (or use Lombok @Data)2public class User {3 private String username;4 private String email;5
6 public String getUsername() { return username; }7 public void setUsername(String username) { this.username = username; }8 public String getEmail() { return email; }9 public void setEmail(String email) { this.email = email; }10}Mistake 3 JSON Key Mismatch Without @JsonProperty
1{ "user_name": "shreyansh" } ← JSON uses snake_case1// ❌ Jackson looks for key "username" not "user_name" → null2private String username;3
4// ✅ Tell Jackson the correct JSON key5@JsonProperty("user_name")6private String username;Mistake 4 Confusing @PathVariable and @RequestParam
1// ❌ Using @RequestParam for a path segment2GET /api/users/423@RequestParam("id") int id ← Wrong — "42" is in the path, not a query param1// ✅ Correct2GET /api/users/423@PathVariable("id") int idMistake 5 Forgetting to Handle Optional @RequestParam
1// ❌ lastName is optional but used without null check2@RequestParam(name = "lastName", required = false) String lastName3return "Hello " + lastName.toUpperCase(); // NullPointerException if lastName is null!1// ✅ Always null-check optional params2@RequestParam(name = "lastName", required = false) String lastName3String name = (lastName != null) ? lastName.toUpperCase() : "unknown";4return "Hello " + name;Mistake 6 Always Returning 200 OK Regardless of Outcome
1// ❌ Returns 200 even when resource is not found2@GetMapping("/user/{id}")3public String getUser(@PathVariable int id) {4 User user = findUser(id);5 if (user == null) return "User not found"; // Still HTTP 200 — misleading!6 return user.getUsername();7}1// ✅ Return appropriate status codes2@GetMapping("/user/{id}")3public ResponseEntity<String> getUser(@PathVariable int id) {4 User user = findUser(id);5 if (user == null) return ResponseEntity.status(HttpStatus.NOT_FOUND)6 .body("User not found");7 return ResponseEntity.ok(user.getUsername());8}17. Summary Cheat Sheet
Annotations Quick Reference
| Annotation | Level | Purpose |
|---|---|---|
@Controller | Class | Marks class as HTTP request handler (view-based) |
@RestController | Class | @Controller + @ResponseBody (for REST APIs) |
@ResponseBody | Method | Return value = HTTP response body, not view name |
@RequestMapping | Class / Method | Maps URL + HTTP method to a handler |
@GetMapping | Method | Shorthand for @RequestMapping(method=GET) |
@PostMapping | Method | Shorthand for @RequestMapping(method=POST) |
@PutMapping | Method | Shorthand for @RequestMapping(method=PUT) |
@PatchMapping | Method | Shorthand for @RequestMapping(method=PATCH) |
@DeleteMapping | Method | Shorthand for @RequestMapping(method=DELETE) |
@RequestParam | Parameter | Extracts query parameters (?key=value) |
@PathVariable | Parameter | Extracts path segments (/resource/{id}) |
@RequestBody | Parameter | Deserializes request body (JSON → Java object) |
@InitBinder | Method | Registers custom type converters for request params |
@JsonProperty | Field | Maps JSON key name to Java field name |
URL Anatomy Reference
1https://example.com/api/users/42/orders?status=active&page=22 │ │ │ │3 │ │ │ └── @RequestParam("page") = "2"4 │ │ └── @RequestParam("status") = "active"5 │ └── @PathVariable("id") = 426 └── @RequestMapping("/api") base pathResponse Building
1ResponseEntity.ok(body) // 200 OK2ResponseEntity.created(uri).body(body) // 201 Created3ResponseEntity.noContent().build() // 204 No Content4ResponseEntity.badRequest().body(msg) // 400 Bad Request5ResponseEntity.notFound().build() // 404 Not Found6ResponseEntity.status(HttpStatus.XXX).body(b) // Any statusKey Decision Guide
1Need to handle HTTP requests?2 → @RestController (REST APIs) or @Controller (HTML templates)3
4Mapping a URL to a method?5 → @GetMapping / @PostMapping / etc. (preferred)6 → @RequestMapping (when you need multiple HTTP methods or complex rules)7
8Reading URL data?9 → Query params (?key=val) → @RequestParam10 → Path segments (/resource/{id}) → @PathVariable11 → Request body (JSON) → @RequestBody12
13Controlling response?14 → Plain return (simple cases, always 200 OK)15 → ResponseEntity (when you need status codes, headers, or conditional responses)Study Guide — Spring Boot Annotations | Spring Boot Series | Concept and Coding
Practice & Implement
Apply what you learned in Spring Boot Annotations
Create a custom annotation `@Validate` with a `minLength` attribute. Write a method that checks if a String field annotated with @Validate meets the minimum length requirement using reflection.
Invalid: username false true
Mastery check
How well can you recall this?
Finished this lesson?