@ResponseStatus Overview
In Spring Boot, the @ResponseStatus
annotation is used to set custom HTTP status codes for controller methods or exception handlers. It allows you to specify an HTTP status without using ResponseEntity
.
✅ Key Features of @ResponseStatus
:
✔ Sets custom HTTP response status codes.
✔ Works with exception handling.
✔ Eliminates the need for ResponseEntity
.
✔ Supports custom error messages for better API responses.
1️⃣ Basic Example: Setting a Custom Response Status
📌 Example: Returning HTTP 201 Created
for a New User
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // Returns HTTP 201 Created
public String createUser(@RequestBody User user) {
return "User created successfully!";
}
}
2️⃣ Using @ResponseStatus
for Exception Handling
Instead of manually returning a ResponseEntity
, you can throw exceptions with @ResponseStatus
to indicate errors.
📌 Example: Custom Exception with @ResponseStatus
@ResponseStatus(HttpStatus.NOT_FOUND) // Returns HTTP 404 Not Found
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
📌 Throwing the Exception in a Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
private final Map<Integer, String> users = Map.of(1, "Ramesh", 2, "Suresh");
@GetMapping("/{id}")
public String getUserById(@PathVariable int id) {
if (!users.containsKey(id)) {
throw new UserNotFoundException("User not found with ID: " + id);
}
return users.get(id);
}
}
Spring Boot @ResponseStatus Annotation Complete Example
In the following application, we demonstrate the usage of the @ResponseStatus annotation. The application simulates a form for retrieving user by their Id. Trying to find the user a by id, if the User is not found then we will throw ResourceNotFoundException.Development Steps
- Create a Spring Boot Application
- Project Structure
- Pom Dependencies
- Java Bean - User.java
- Define Custom Exception
- Create REST Controller - UserController.java
- Run Application - Application.java
- Testing from Postman Client
1. Create a Spring Boot Application
>> Create Spring Boot Project in Spring Tool Suite [STS]
3. Pom Dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
4. Java Bean - User.java
package net.javaguides.springboot;
public class User {
private Integer id;
private String name;
public User() {}
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5. Define Custom Exception - ResourceNotFoundException.java
package net.javaguides.springboot;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1 L;
private String message;
public ResourceNotFoundException(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
6. Create REST Controller - UserController.java
package net.javaguides.springboot;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/users/{id}")
public ResponseEntity < User > getUser(
@PathVariable(value = "id") Integer userId) throws ResourceNotFoundException {
Map < Integer, User > map = new HashMap < > ();
map.put(1, new User(1, "Ramesh"));
map.put(2, new User(2, "Tony"));
map.put(3, new User(3, "Tom"));
if (!map.containsKey(userId)) {
throw new ResourceNotFoundException("Resource not found for " + userId);
}
return ResponseEntity.ok(map.get(userId));
}
}
7. Run Application - Application.java
mvn spring-boot:run
8. Testing from Postman Rest Client
Using @ResponseStatus
for Different HTTP Status Codes

@ResponseStatus
vs ResponseEntity

📌 Example: Using ResponseEntity
Instead of @ResponseStatus
@GetMapping("/{id}")
public ResponseEntity<String> getUserById(@PathVariable int id) {
if (!users.containsKey(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("User not found with ID: " + id);
}
return ResponseEntity.ok(users.get(id));
}
✅ Use ResponseEntity
when you need dynamic responses, otherwise @ResponseStatus
is sufficient.
Comments
Post a Comment
Leave Comment