@ResponseStatus in Spring: What It Is and How to Use It
@ResponseStatus is a Spring annotation used to mark a method or exception class with a specific HTTP status code. It tells Spring what HTTP status to send back in the response when that method runs or that exception is thrown.How It Works
Imagine you are sending a letter and want to mark it with a special stamp to show its importance. In Spring, @ResponseStatus acts like that stamp for HTTP responses. When you add this annotation to a method or an exception class, Spring automatically adds the specified HTTP status code to the response sent to the client.
This means you don't have to write extra code to set the status manually. For example, if a method creates a new resource, you can mark it with @ResponseStatus(HttpStatus.CREATED) so the client knows the creation was successful with status 201.
Similarly, if an exception is marked with @ResponseStatus, Spring will send the defined status code whenever that exception happens, making error handling cleaner and more consistent.
Example
This example shows a simple Spring REST controller method that uses @ResponseStatus to send a 201 Created status when a new item is added.
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController public class ItemController { @PostMapping("/items") @ResponseStatus(HttpStatus.CREATED) public String addItem(@RequestBody String item) { // Imagine saving the item here return "Item added: " + item; } }
When to Use
Use @ResponseStatus when you want to clearly define the HTTP status code your controller method or exception should return without writing extra code to set it manually.
Common real-world uses include:
- Marking successful creation of resources with
HttpStatus.CREATED(201). - Indicating that a resource was not found by annotating a custom exception with
HttpStatus.NOT_FOUND(404). - Signaling forbidden access with
HttpStatus.FORBIDDEN(403) on exceptions.
This helps keep your code clean and your API responses clear and consistent.
Key Points
- @ResponseStatus sets HTTP status codes declaratively on methods or exceptions.
- It simplifies response handling by avoiding manual status code setting.
- Works well for REST APIs to communicate success or error states clearly.
- Can be used on custom exception classes to map exceptions to HTTP statuses.
- Improves code readability and consistency in Spring web applications.
Key Takeaways
@ResponseStatus sets HTTP status codes automatically for methods or exceptions in Spring.@ResponseStatus to map them to HTTP statuses.