📘 Premium Read: Access my best content on
Medium member-only articles
— deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount):
My Udemy Courses - Ramesh Fadatare
— All my Udemy courses are real-time and project oriented courses.
In this short article, we will learn how to use Spring Boot @ResponseStatus annotation in a Spring Boot application. We create a Spring Boot RESTful application to demonstrate the annotation.
@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
@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 publicclassUserNotFoundExceptionextendsRuntimeException { publicUserNotFoundException(String message) { super(message); } }
private final Map<Integer, String> users = Map.of(1, "Ramesh", 2, "Suresh");
@GetMapping("/{id}") publicStringgetUserById(@PathVariable int id) { if (!users.containsKey(id)) { thrownewUserNotFoundException("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
There are many ways to create a Spring Boot application. You can refer to the below articles to create a Spring Boot application.
Refer to the project structure or packaging structure in the next step.
2. Project Structure
This is the project structure of the Spring Boot application that we are going to create -
3. Pom Dependencies
This is the Maven build file. The spring-boot-starter-web is a starter for building web applications using Spring MVC. It uses Tomcat as the default embedded container.
Let's create a simple UserController with users REST API, which returns a User by ID, if the User is not found, then we will throw ResourceNotFoundException.
packagenet.javaguides.springboot;
importjava.util.HashMap;
importjava.util.Map;
importorg.springframework.http.ResponseEntity;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RestController;
@RestControllerpublicclassUserController {
@GetMapping("/users/{id}")
publicResponseEntity < User > getUser(
@PathVariable(value="id") IntegeruserId) throwsResourceNotFoundException {
Map<Integer, User> map =newHashMap < > ();
map.put(1, newUser(1, "Ramesh"));
map.put(2, newUser(2, "Tony"));
map.put(3, newUser(3, "Tom"));
if (!map.containsKey(userId)) {
thrownewResourceNotFoundException("Resource not found for "+ userId);
}
returnResponseEntity.ok(map.get(userId));
}
}
7. Run Application - Application.java
Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.
Let's run this Spring Boot application from either Eclipse IDE by right-clicking Run As - Java Application.
Or you can use the below maven command to run:
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)) { returnResponseEntity.status(HttpStatus.NOT_FOUND) .body("User not found with ID: " + id); } returnResponseEntity.ok(users.get(id)); }
✅ Use ResponseEntity when you need dynamic responses, otherwise @ResponseStatus is sufficient.
Comments
Post a Comment
Leave Comment